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发布于 2010-06-18 02:09:31
您需要改用preg_replace():
$_POST['exclude'] = preg_replace( '/' . preg_quote( $match[1], '/' ) . '/', "", $_POST['exclude'], 1, $i );$_POST‘’exclude‘后面的变量是一个limit变量,您可以在上面的链接中看到。
preg_quote()函数在日期字段中不是必需的,但因为它是一个变量,所以可能需要包含特殊的正则表达式字符。
https://stackoverflow.com/questions/3064312
复制相似问题