Im using preg_replace to replace keywords in text with a href tag, my regex is working awesome, right now my code is:
$newstring2 = preg_replace(\"/\\p{L}*?\
If it must be done with regex I think PCRE verbs are your best option. Exclude all links then search for the term with word boundaries.
<a[\S\s]+?<\/a>(*SKIP)(*FAIL)|\bTERM\b
Demo: https://regex101.com/r/KlE1kc/1/
an example of a flaw with this though is if the a
ever had a </a>
in it. e.g. onclick='write("</a>")'
a parser is really the best approach. There are a lot of gotchas with HTML and regexs.
How about this with negative lookahead. Regex
Explanation: capture all the keyword that is called text
and replace with it some link but don't capture those keywords that have </a>
after it.
$re = '/(text)(?!<\/a>)/m';
$str = 'this is sample text about something what is text.
this is sample <a href=\'somelink.php\'>text</a> about something what is <a href=\'somelink.php\'>text</a>.';
$subst = '<a href=\'somelink.php\'>$1</a>';
$result = preg_replace($re, $subst, $str);
echo $result;
Output:
this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>.
this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>.
DEMO: https://3v4l.org/DVTB1