Using regular expressions to replace html text content in php

requirement: specify anchor text to replace the content edited by the rich text box

current implementation: use the rule: $matches = preg_replace ("/\ > ([^ < >] + |. *?) Clothes ([^ < >] + |. *?) < / ","> ${1} @ ${2} <", $str);
this rule can replace "clothes" with "@" in all text content. The reason for not using str_replace directly is that "@" is actually a link with a tag. If a replacement keyword appears in the title within a html tag, it will be replaced incorrectly.

Another drawback of the

rule is that for the content edited in the rich text box, if the keyword is already in a tag (for example: XXX clothes ), the a tag will be nested within the a tag.

but currently there is no suitable rule to match the content of html tags other than a tag, so I first used another rule here: $matches1 = preg_replace ("/ ] + |. *?) > ([^ < >] + |. *?) Clothes ([^ < >] + |. *?) < / "," ${2}-=-${3} < ", $str);
replace the keyword" clothes "in the a tag with the special symbol-= -, and then use the regular: $matches = preg_replace (" /\ > ([^ < >] + |. *?) Clothes ([^ < >] + |. *?) < / ","> ${1} @ ${2} <", $str);
replace the keywords that need to be replaced, and finally replace the special symbol-=-back to the original keyword.

but this method needs to be replaced three times to achieve the final result, and the performance is not very good, so I would like to ask here whether there is a regular replacement to meet this requirement?

Oct.20,2021
Menu