正規表現は 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 解析には適していません ;) )