Regex with preg_replace in PHP -


it's long time ago haven't played php , regex , i'd find regex following work.

my string contains :

<pre code="...">some piece of code</pre> other non code content <pre code="...">some piece of code</pre> other non code content... 

the goal replace <pre>code</pre> by&

code
...`

where "code" inside <pre>&</pre> should escaped htmlspecialchars...

i've tried few regex didn't succeed.

any idea?

thanks

generally, using regex parse html bad idea. there plenty of simple scenarios, regex enough solve particular problem, , great.

i argue in case using regex bad idea, not cover cases , insecure. possibly trying prevent xss vulnerabilities, , regex based solutions error-prone.

but completeness sake:

preg_replace_callback(     '/(<\\s*pre(?:\\s[^>]+)?>)(.*?)(<\\/\s*pre\s*>)/',     function ($match) {         return $match[1].htmlspecialchars($match[2]).$match[3];     },     $html ); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -