How to Exclude Matching Keywords within Specific HTML Tags Using Regular Expressions in PHP?

Mary-Kate Olsen
Release: 2024-10-20 13:30:29
Original
340 people have browsed it

How to Exclude Matching Keywords within Specific HTML Tags Using Regular Expressions in PHP?

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!