【问题标题】:str_replace match only first instancestr_replace 仅匹配第一个实例
【发布时间】:2010-06-17 18:06:58
【问题描述】:

Get all text between tags with preg_match_all() or better function?的后续问题

给定以下 POST 数据:

2010-June-3
<remove>2010-June-3</remove>
2010-June-15
2010-June-16
2010-June-17
2010-June-3
2010-June-1

我只想删除 2010 年 6 月 3 日的第一个实例,但以下代码会删除所有数据。

$i = 1;
$pattern = "/<remove>(.*?)<\/remove>/";
preg_match_all($pattern, $_POST['exclude'], $matches, PREG_SET_ORDER);
    if (!empty($matches)) { 
        foreach ($matches as $match) {
            // replace first instance of excluded data
            $_POST['exclude'] = str_replace($match[1], "", $_POST['exclude'], $i);  
        }
   }

echo "<br /><br />".$_POST['exclude'];

这回响:

<remove></remove>
2010-June-15
2010-June-16
2010-June-17
2010-June-1

它应该回显:

<remove>2010-June-3</remove>
2010-June-15
2010-June-16
2010-June-17
2010-June-3
2010-June-1

【问题讨论】:

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


    【解决方案1】:

    您需要改用preg_replace():

    $_POST['exclude'] = preg_replace( '/' . preg_quote( $match[1], '/' ) . '/', "", $_POST['exclude'], 1, $i );
    

    $_POST['exclude'] 之后的变量是limit 变量,如您在上面的链接中所见。

    preg_quote() 函数在日期字段中不是必需的,但由于它是一个变量,因此可能需要包含特殊的正则表达式字符。

    【讨论】:

    • Kerry,您可能想为preg_quote 提供$delimiter 参数,以防万一……以及实际调用preg_replace。
    • 好点——谢谢。我觉得很有趣/很遗憾我没有用 preg_replace 替换代码
    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 2012-03-29
    • 1970-01-01
    • 2018-11-02
    • 2023-01-19
    • 2014-06-30
    相关资源
    最近更新 更多