Jump to content
Larry Ullman's Book Forums

Perhaps This'Ll Be My Final Regex Question


Recommended Posts

My current regex conundrum is as follows:

 

I have used the following regex pattern to capture all the HTML between a bunch of pre tags (of which there are many sets):

 

/(?<=<pre>)([\s\S]+?)(?=\<\/pre>)/

 

All the content (the HTML between the pre tags) is stored in group reference $1. I can output the results as follows:

 

echo preg_replace('/(?<=<pre>)([\s\S]+?)(?=\<\/pre>)/','$1',$content);

 

However, because the HTML contains all sorts of angle brackets, etc., you can't actually see anything. As such, I want to run the content (i.e., $1) through a function like htmlentities as follows:

 

echo preg_replace('/(?<=<pre>)([\s\S]+?)(?=\<\/pre>)/',htmlentities('$1'),$content);

 

But this doesn't work. Is this even possible (what I'm trying to do), or is it just that my syntax is no good?

 

Thank you all in advance.

Link to comment
Share on other sites

Hi HartleySan,

 

You can use functions inside preg_replace however not in it's default implementation. PREG_REPLACE has a special modifier 'e' which when placed after the pattern causes references in the replacement element to be evaluated as PHP code. Here's an example from the PHP manual:

 

<?php
preg_replace("/(<\/?)(\w+)([^>]*>)/e", 
            "'\\1'.strtoupper('\\2').'\\3'", 
            $html_body);
?>

 

I've never had cause to use it but thats the premise.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...