str_replace 仅匹配第一个实例
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 preg_replace() 代替:
后面的变量$_POST['exclude'] 是一个
limit
变量,正如您在上面的链接中看到的那样。日期中不需要 preg_quote() 函数字段,但由于它是一个变量,因此可能需要包含特殊的正则表达式字符。
You need to use preg_replace() instead:
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.