Jump to content

[SOLVED] Need help on a specific match, content of a "<pre>" tag ...


adrianTNT

Recommended Posts

Hello, I have this text:

 

$my_text= '<pre class="brush: plain">

<div class="header">

<a href="#">home</a>

<a href="#">products</a>

<a href="#">services</a>

</div>

</pre>';

 

I need to get all that content inside the "<pre>..</pre>" tag and convert it to htmlentities.

The "class" is different in more situations so I need to match:

 

<pre [anything]>[GIVE ME THIS]</pre>

 

Does that make sense? :)

Thank you in advance.

ok, and what is the right way to convert the tag contents to html entities, I thought this would work, I was wrong:

 

$my_text= '<pre class="brush: plain">
<div class="header">
<a href="#">home</a>
<a href="#">products</a>
<a href="#">services</a>
</div>
</pre>';

echo preg_replace("<pre[^>]*>(.*?)</pre>", htmlentities("$1"), $my_text);

Warning: Unknown modifier ']'

echo preg_replace("<pre[^>]*>(.*?)</pre>", htmlentities("$1"), $my_text);

 

 

 

Ahhh....

 

It can't be <pre.... as the pattern. It needs delimiters.  Also, you'll need to use the e flag and put the function name in quotes if you want to do that.

 

 

echo preg_replace("~<pre[^>]*>(.*?)</pre>~e", "htmlentities('$1')", $my_text);

$my_text= '<pre class="brush: plain">
<div class="header">
<a href="#">home</a>
<a href="#">products</a>
<a href="#">services</a>
</div>
</pre>';
echo preg_replace("~<pre[^>]*>(.*?)</pre>~e", "htmlentities('$1')", $my_text);

This one returns the string unchanged.

- Maybe the forum is formating the code differently and I am pasting the wrong thing?

- Or the intitial text needs to be in double quotes?

Sorry to bother you, I thought it was easyer.

Yep, just add the s modifier after the pattern (I also added a word boundary and made the search case insensitive):

 

preg_replace('~<pre\b[^>]*>(.*?)</pre>~ise', 'htmlentities(\'$1\')', $my_text);

If you want to retain the pre tags around the matched content, just grab the tags and use them in the replacement:

 

preg_replace('~(<pre\b[^>]*>)(.*?)(</pre>)~ise', '\'$1\' . htmlentities(\'$2\') . \'$3\'', $my_text);

I'm grabbing the last match to be sure the casing is right. Guess it's not necessary though.

I'm almost there :)

preg_replace('~(<pre\b[^>]*>)(.*?)(</pre>)~ise', '\'$1\' . htmlentities(\'$2\') . \'$3\'', $my_text);

Is almost perfect, just that it made html entities of the class="brush: plain" too, how to change that to only start the html entities right after that?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.