我有一个html字符串,我只需要删除第一个<h3>标记。
我尝试了下面的代码,但删除了所有<h3>标记
$final = preg_replace('#<h3>(.*?)</h3>#', '', $html);
echo $final;发布于 2016-06-19 04:46:27
只需RTM http://php.net/manual/en/function.preg-replace.php向preg_replace添加第四个参数
<?php
$html = '
<h3>one</h3>
<h3>two</h3>
<h3>tree</h3>
zzz
';
$final = preg_replace('#<h3>(.*?)</h3>#', '', $html, 1);
echo $final;在http://sandbox.onlinephpfunctions.com/上测试
发布于 2016-06-19 04:38:00
一个好的起点始终是PHP docs。如果你看一下那里,你会发现preg_replace()的第四个(可选)参数是要进行的替换次数。我认为将它添加到你的函数调用中应该能起到作用。
发布于 2016-06-19 04:38:33
对于每个http://php.net/manual/en/function.preg-replace.php,一个可选参数限制执行的替换次数。我想你想要的是:
 $final = preg_replace('#<h3>(.*?)</h3>#', '', $html, 1);https://stackoverflow.com/questions/37901393
复制相似问题