str_replace 仅匹配第一个实例

发布于 2024-09-06 17:12:23 字数 1019 浏览 3 评论 0原文

使用 preg_match_all() 或更好的函数获取标签之间的所有文本? 的后续问题

给出以下 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-June-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

A followup question to Get all text between tags with preg_match_all() or better function?

Given the following POST data:

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

I'm wanting to remove ONLY the first instance of 2010-June-3, but the following code removes all the data.

$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'];

This echos:

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

It should echo:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送君千里 2024-09-13 17:12:23

您需要使用 preg_replace() 代替:

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

后面的变量$_POST['exclude'] 是一个 limit 变量,正如您在上面的链接中看到的那样。

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

You need to use preg_replace() instead:

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

The variable after the $_POST['exclude'] is a limit variable, as you can see in the link above.

The preg_quote() function wasn't necessary in the date field, but because its a variable, it may be needed to include the special regular expression characters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文