December 21st, 2011, 05:15 AM
Preg replace only outside HTML tags
i need to search and replace keywords, but these keywords should not be html tags.
for example if the user inputs "strong"/ "class", it should replace all "strong" Or "class" with a keyword of my choice, but all html tag <strong> and all attributes "class" should remain as is.
been trying all combinations but just cant get it .
Thanks in advance.
PS: i want to use preg replace and NOT DOM.
December 21st, 2011, 04:40 PM
Do a preg_split() to separate the text into parts that alternate as HTML tags and raw text, and do the rest of the replacing on only the text parts.
I'm too lazy to look up the syntax to make sure I'm right, but I think I am.
$parts = preg_split('#</?[a-z][^>]*>#i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
December 22nd, 2011, 12:58 AM
Not to take anything away from requinix's idea, which might be exactly what you need.
Just another potential direction depending on your inclination: Are you familiar with lookarounds? To give you an example, this regex:
matches the word "strong" that is neither followed by a ">" nor preceded by a "<".
Wishing you a fun day
Last edited by ragax; December 22nd, 2011 at 12:59 AM.
Reason: Improved punctuation.