我同意 Brian 的观点,即正则表达式不是解析 HTML 的好方法,但如果您必须使用正则表达式,您可以尝试将字符串拆分为标记,然后在每个标记上运行您的正则表达式。
我preg_split
用来分割 HTML 标签和短语上的字符串<sup>®</sup>
——这将留下不是上标®
或标签的文本作为标记。然后对于每个令牌,®
可以替换为<sup>®</sup>
:
$regex = '/(<sup>®<\/sup>|<.*?>)/i';
$original = '<div>asd® asdasd. asd<sup>®</sup>asd <img alt="qwe®qwe" /></div>';
// we need to capture the tags so that the string can be rebuilt
$tokens = preg_split($regex, $original, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
/* $tokens => Array
(
[0] => <div>
[1] => asd® asdasd. asd
[2] => <sup>®</sup>
[3] => asd
[4] => <img alt="qwe®qwe" />
[5] => </div>
)
*/
foreach ($tokens as &$token)
{
if ($token[0] == "<") continue; // Skip tokens that are tags
$token = substr_replace('®', '<sup>®</sup>');
}
$tokens = join("", $tokens); // reassemble the string
// $tokens => "<div>asd<sup>®</sup> asdasd. asd<sup>®</sup>asd <img alt="qwe®qwe" /></div>"
请注意,这是一种幼稚的方法,如果输出未按预期格式化,它可能不会像您想要的那样解析(同样,正则表达式不适合 HTML 解析;))