【问题标题】:Php Str_replace with a for loopPHP Str_replace 与 for 循环
【发布时间】:2012-06-04 13:42:50
【问题描述】:

我正在尝试为每个textarea 命名,以便以后可以使用它们将它们发送回数据库。 使用这段代码,我得到了一些奇怪的结果,我猜是因为我使用了str_replace

代码如下:

$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);   
}                               
}

来自数据库xa1xb2xcxd3xe4xcxa5xb6xc(description2)的示例字符串

如您所见,我正在尝试将其全部循环并为 $totalteknisk 赋予值 1。

我愿意就如何使这项工作提出建议。

【问题讨论】:

  • 这些“奇怪的结果”会是什么?
  • 它没有给出值 1,2 ,3 ,4, 5, 6 ,7 ,8 等,但它重复值 1,2,3,4 1,2,3,4 1 ,2,3,4 1,2,3,4 然后转到 5,6,7,8 5,6,7,8 .. 等

标签: php mysql str-replace preg-match-all


【解决方案1】:

我通过使用 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;

我还建议您不要只使用数字作为文本区域中的“名称”属性。您可以考虑使用其他名称,例如fields[$count],然后通过$_POST['fields'] ... 引用它

【讨论】:

  • 是的,这也是我的计划,但我需要一些东西来开始:D 了不起的家伙!真的谢谢!
猜你喜欢
  • 2010-12-16
  • 2023-04-02
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
相关资源
最近更新 更多