How to Match Keywords Outside of Anchor Tags Using PHP Regex?

Patricia Arquette
Release: 2024-10-20 13:29:02
Original
259 people have browsed it

How to Match Keywords Outside of Anchor Tags Using PHP Regex?

Matching Keywords Outside HTML Anchor Tags () Using PHP Regular Expression

In web development, there might arise situations where you need to match and replace keywords within HTML content while avoiding certain specific areas, such as hyperlinks. This can be achieved using PHP regular expressions.

Problem Statement:

The task at hand is to find a regular expression pattern that matches the keyword "keyword" but excludes instances that are enclosed within anchor tags (keyword).

Solution:

To address this problem effectively, the following PHP regular expression can be utilized:

<code class="php">$str = preg_replace('~Moses(?!(?>[^<]*(?:<(?!/?a\b)[^<]*)*)</a>)~i',
                    '<a href="novo-mega-link.php"></a>', $str);</code>
Copy after login

Explanation:

  • Moses: This part simply matches the keyword "Moses."
  • (?!: This denotes the beginning of a negative lookahead assertion.
  • (?>[^<]*(?:<(?!/?ab)[^<]*)*): This part creates a recursive pattern to identify any number of non-HTML tag characters or nested tags that are not opening anchor tags.
  • : Matches the closing anchor tag.
  • ): This parenthesis closes the negative lookahead assertion.
  • ~i: The case-insensitive modifier makes the pattern work for both upper and lower case "Moses."

Working Principle:

The regular expression initially matches "Moses." However, if the following conditions are met, it will not perform a match:

  • The keyword must be followed by a sequence of non-HTML characters.
  • The keyword must not be followed by an opening anchor tag.
  • The keyword must be followed by a valid closing anchor tag.

If all these conditions are fulfilled, the pattern will not match the keyword. Consequently, it will be excluded from replacement.

The above is the detailed content of How to Match Keywords Outside of Anchor Tags Using PHP Regex?. 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!