我有一个textarea用户写这样:
重点是回响蓝花3次等,而没有数字的鲜花则回响1次。
这是我的代码:
$str = $_POST['tekst'];
$input = explode("\n", $str);
foreach($input as $line)
{
preg_match("/\d+/", $line, $matches);
$line = preg_replace("/\d+/",'' ,$line);
$number = (isset($matches[0]))?$matches[0]:1;
if(strlen($line)>0){
foreach ($line as $k=>$val)
{
$temp_second_field = $number[$k];
for ($i = 0 ; $i < $temp_second_field ; $i++ )
{
echo $val;
}
}
}
}
答案 0 :(得分:1)
这是因为$ line不是数组,而是字符串。尝试替换它:
// foreach ($line as $k=>$val)
// {
// $temp_second_field = $number[$k];
// for ($i = 0 ; $i < $temp_second_field ; $i++ )
// {
// echo $val;
// }
// }
//$temp_second_field = $number[$k];
用这个:
for ($i = 0 ; $i < $number ; $i++ )
{
echo $line;
}
答案 1 :(得分:1)
我认为,第二个foreach:
foreach ($line as $k=>$val)
是一个错误 - 您是否尝试逐个字符串迭代?
看看这段代码:
$str = $_POST['tekst'];
$input = explode("\n", $str);
foreach($input as $line)
{
preg_match("/\d+/", $line, $matches);
$line = preg_replace("/\d+/",'' ,$line);
$number = (isset($matches[0]))?$matches[0]:1;
if(strlen($line)>0){
echo str_repeat( $line."\n", $number );
}
}