替换所有不属于HTML代码的匹配项


Replace all matches that are not part of HTML code

我有这样的输入:

<h2 class="role">He played and an important role</h2>

而需要替换的角色,却不在类中。

棘手的是,它可能是class="group role something"左右,所以我基本上只想搜索真实的文本而不是html,但我需要返回一切。

我在PHP中,没有一个真正好的起点…

最好不要使用preg_来解析HTML,使用dom:

$input = '<h2 class="role">He played and an important role</h2>';
$dom = new domDocument('1.0', 'utf-8'); 
$dom->loadHTML($input); 
$dom->preserveWhiteSpace = false; 
$element = $dom->getElementsByTagName('h2'); // <--- change tag name as appropriate
$value = $element->item(0)->nodeValue;
// change $value here...

最好使用DOM来操作HTML,但这里有一个正则表达式解决方案。

如果>出现在字符串前面的<之前,则不进行替换。

$input = '<h2 class="role">He played and an important role</h2>';
$input = preg_replace( '/role(?![^<>]*>[^<>]*(?:<|$))/', 'new role', $input );
echo $input;    
// <h2 class="role">He played and an important new role</h2>