长文本中有字符串,如:
<fn id="T1FN1"> anytext <p> sometext </p> </fn>
<fn id="T2FN1"> anytext <p> sometext </p> </fn>
<fn id="T2FN2"> anytext <p> sometext </p> </fn>
<fn id="F12FN5"> anytext <p> sometext </p> </fn>
等等。。。
我想找到文本中的<fn </fn>
并删除<p> and </p>
仅从这些字符串中,<p> and </p>
之间的字符串不会被删除。我试着做了一些预置换,但没有成功。
您可以尝试使用嵌套的正则表达式:
$html = '<fn id="T1FN1"> anytext <p> sometext </p> </fn>
<fn id="T2FN1"> anytext <p> sometext </p> </fn>
<fn id="T2FN2"> anytext <p> sometext </p> </fn>
<fn id="F12FN5"> anytext <p> sometext </p> </fn>';
preg_replace_callback('/<fn[^>]*>.*?<p>.*?</p>.*?</fn>/', function($matches){
return preg_replace('/<p>|</p>/', '', $matches[0]);
}, $html);
注意:这个语法需要PHP 5.3+。如果你运行的是旧版本,请告诉我,我会提供语法。
试试这个:
$s=<<<HDOC
<fn id="T1FN1"> anytext <p> sometext </p> </fn>
<fn id="T2FN1"> anytext <p> sometext </p> </fn>
<fn id="T2FN2"> anytext <p> sometext </p> </fn>
<fn id="F12FN5"> anytext <p> sometext </p> </fn>
<fnn id="F12FN5"> anytext <p> these tags stay </p> </fnn>
<p> some text that stays with tags </p>
HDOC;
$pattern = '/(<fn[^>]*>[^<]*)<p>([^<]*)<'/p>([^<]*<'/fn>)/';
$replace = ''1'2'3';
echo htmlspecialchars(preg_replace($pattern, $replace, $s));
注意:只能找到一对<p></p>
,anaytext中不能有标签