2

I am using the following to find and replace words within string $content:

$replacedcontent = preg_replace('/\b'.$term_name.'\b/u', '<a class="highlight">'.$term_name.'</a>', $content);

Is there a simple way using regex to only replace words if they are not immediately preceded by an <a href="[link to somewhere]"> tag?

1 Answer 1

3

Use a negative lookahead assertion. This would replace all the $term_name which was not present inside the anchor tag.

preg_replace('/\b'.$term_name.'\b(?!(?:(?!<\/?a\b[^>]*>).)*?<\/a>)/u', '<a class="highlight">'.$term_name.'</a>', $content);

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.