使用REGEX替换两个HTML标记之间的所有“foo”(PHP代码)

时间:2011-05-14 07:46:43

标签: php regex

我想要一个正则表达式代码,将所有“foo”字符串替换为“bar”,在html标记之前>< /预>

这是一个例子:

< html>
< p> blah blah blah foo try foo< /p>
< pre> foo try foo word foofoo < /pre>
< /html>

应该

< html>
< p> blah blah blah foo try foo< /p>
< pre> bar try bar word barbar < /pre>
< /html>

所以,这意味着pre之前的所有foo应该替换为。

我试图使用这个正则表达式模式,但它不起作用。

do {
$string = preg_replace('/< pre>([^)]*)foo([^)]*< /pre>)/U', '\1boo\2', $string, -1,$count);
}while($count != 0);
echo $string;
对不起我的英语 谢谢,

3 个答案:

答案 0 :(得分:5)

$string = '< html>
< p> blah blah blah foo try foo< /p>
< pre> foo try foo word foofoo < /pre>
< /html>';
$string = preg_replace('/foo(?=(?:.(?!< pre>))*< \/pre>)/Um', 'boo', $string);
echo $string;

答案 1 :(得分:2)

您可以使用DOMDocument提取HTML标记的文本内容,对文本执行简单的str_replace并更新DOM。

答案 2 :(得分:1)

首先,去获取Simple HTML Dom

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find the first pre (you can change this or find an array based on documentation on website to suit your needs, but I will make it just for the first pre for now
$html->find('pre', 0)->plaintext = str_replace('foo', 'bar', $html->find('pre', 0)->plaintext);

//Echo HTML
echo $html;