Jump to content
Larry Ullman's Book Forums

There Must Be A Good Regex For This...


Recommended Posts

I basically have a bunch of pre tags surrounded by a bunch of p tags, and it's all stored in a string. For example, imagine the following stored in a variable called $string:

 

<p>Text here.</p>

<p>Text here.</p>

<p>Text here.</p>

<pre>Code here.</pre>

<p>Text here.</p>

<pre>Code here.</pre>

<p>Text here.</p>

<p>Text here.</p>

<pre>Code here.</pre>

<p>Text here.</p>

 

Anyway, I need to use the htmlentities function or something similar on the code in the pre tags to get the code to display, but I'm trying to come up with a regex or set of regexs to separate the stuff within the pre tags with everything outside of it for getting the code to display.

 

I was thinking about something like the following:

 

$string = // The above HTML

$pattern = '$<pre>(*)</pre>$g';

$replacement = '<pre>' . htmlentities('$\1$') . '</pre>';

preg_replace($pattern,$replacement,$string);

 

Would that work, or am I just crazy?

 

I'll keep spit balling, and posting my ideas up here as I think of them, unless someone can help in the meantime. Thank you.

Link to comment
Share on other sites

Using that awesome tool you recommended, I was able to find what I was looking for. Here's the basic search and replace:

 

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

 

<pre>$1</pre>

 

Because just about anything can go in pre tags, I had to be very vague with my regex, which makes it somewhat inefficient, but at the level I'm using it, I doubt the user will notice.

  • Upvote 1
Link to comment
Share on other sites

I looked into that guy who made that regex tool, and apparently he's a big deal in the Flash community. Very interesting.

 

I think I'm finally starting to become comfortable with regexes too. It's taken forever, but the old adage of "Practice makes perfect" is 100% true. It has been a frustrating ascension to comprehension at times though.

 

Once you get them down though, you suddenly want to use regexes for everything (even when you don't need them). They're a lot of fun and super useful.

Link to comment
Share on other sites

 Share

×
×
  • Create New...