Matching Keywords Outside HTML Anchor Tags Using Regular Expressions in PHP
Matching keywords in HTML text can be a challenge, especially when it comes to avoiding matches within specific tags like anchor tags (keyword" and "already linked keyword ".
The Solution
The provided PHP code leverages a complex regex to achieve the desired result:
<code class="php">$str = preg_replace('~Moses(?!(?>[^<]*(?:<(?!/?a\b)[^<]*)*)</a>)~i', '<a href="novo-mega-link.php"></a>', $str);</code>
Understanding the Regex
The regex comprises a main expression and a negative lookahead:
Explanation
The regex works by first matching the keyword. It then employs a negative lookahead to check for the presence of a closing tag without an intervening tag. If the lookahead succeeds, it means the keyword is enclosed within an anchor element, so the match is discarded. Otherwise, the main expression matches the keyword, and it is replaced with the specified HTML code.
Implementation
The code provided assigns the modified string to the $str variable. The regex can be modified as needed to match different keywords or HTML tags.
The above is the detailed content of How to Exclude Matching Keywords within Specific HTML Tags Using Regular Expressions in PHP?. For more information, please follow other related articles on the PHP Chinese website!