[英]Php Str_replace with a for loop
I'm trying to give each textarea
a name so I can use them later to send back to the database. 我正在尝试给每个textarea
命名,以便以后可以使用它们将其发送回数据库。 With this code I got some weird results and I guess its because I use str_replace
. 有了这段代码,我得到了一些奇怪的结果,我猜是因为我使用了str_replace
。
Here's the code: 这是代码:
$description2 = mysql_result($product, 0, 'productDescription2');
$totalteknisk = preg_match_all('/x(a|b|d|e)/', $description2, $matches);
$searchArray = array('xa', 'xb', 'xc', 'xd', 'xe');
if ($description2 !=""){
for($z=1;$z <= $totalteknisk; $z++){
$xa = '<textarea name="'. $z .'" style="background-color:#FFFFFF;resize: none; height: 20px; width: 200px;">';
$z++;
$xb ='</textarea><textarea name="'. $z .'" style="background-color:#FFFFFF;resize: none; height: 20px; width: 200px;">';
$z++;
$xc = '</textarea><br>';
$xd = '<textarea name="'. $z .'" style="background-color:#EAF2D3;resize: none; height: 20px; width: 200px;">';
$z++;
$xe = '</textarea><textarea name="'. $z .'" style="background-color:#EAF2D3;resize: none; height: 20px; width: 200px;">';
$replaceArray = array($xa, $xb, $xc, $xd, $xe);
$teknisk .= str_replace($searchArray, $replaceArray, $description2);
}
}
Example string from database xa1xb2xcxd3xe4xcxa5xb6xc
(description2) 数据库xa1xb2xcxd3xe4xcxa5xb6xc
字符串xa1xb2xcxd3xe4xcxa5xb6xc
(description2)
As you can see I'm trying to just loop it all and give it a value 1 to $totalteknisk
. 如您所见,我试图将其全部循环,并将其值1赋予$totalteknisk
。
I'm open for suggestions on how I can make this work. 我愿意就如何进行这项工作提出建议。
I solved it a bit differently, by using preg_replace_callback(...) 我通过使用preg_replace_callback(...)解决了一些问题
$description2 = 'xa1xb2xcxd3xe4xcxa5xb6xc';
$html = preg_replace_callback('/x(?:a|b|c|d|e)/', function($match) {
static $count;
$count++;
switch($match[0]) {
case 'xa':
return "<textarea name=\"$count\" style=\"background-color:#FFFFFF;resize: none; height: 20px; width: 200px;\">";
case 'xb':
return "</textarea><textarea name=\"$count\" style=\"background-color:#FFFFFF;resize: none; height: 20px; width: 200px;\">";
case 'xc':
return "</textarea><br />";
case 'xd':
return "<textarea name=\"$count\" style=\"background-color:#EAF2D3;resize: none; height: 20px; width: 200px;\">";
case 'xe':
return "</textarea><textarea name=\"$count\" style=\"background-color:#EAF2D3;resize: none; height: 20px; width: 200px;\">";
}
}, $description2);
$teknisk .= $html;
I would also suggest, that you dont use only numbers for the 'name' attribute in the textareas. 我还建议不要在textareas中仅对“ name”属性使用数字。 You may should consider using another name, like fields[$count]
and then refer to it by $_POST['fields'] ...
您可能应该考虑使用其他名称,例如fields[$count]
,然后通过$_POST['fields'] ...
引用它$_POST['fields'] ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.