Jump to content

ereg_replace() question


fishfin

Recommended Posts

I'm trying to search a string for a specific string and then replace both that string and the things around it. (I'm sure that sentence was confusing and you probably don't have any idea what I meant so I'll give an example.)

 

I have a string that goes something like this: "<p>Today I went to the zoo and did this and that..</p><p>Well today I didn't do anything interesting...</p><p>Today I played a new game...</p>"

 

I want to be able to search threw it for a specific word or series of words (I'll use the word 'zoo' for my example) and for the string to be changed to something like this: "<h2>Today I went to the zoo and did this and that..</h2><p>Well today I didn't do anything interesting...</p><p>Today I played a new game...</p>"

 

This is what I was trying but it doesn't seem to work:

 

$string1 = ereg_replace("<p>(.+)" . $search . "(.+)</p>", "<h2>\\1" . $search . "\\2</h2>", $string1);

Link to comment
https://forums.phpfreaks.com/topic/118207-ereg_replace-question/
Share on other sites

Use PREG and make the patterns lazy:

 

<pre>
<?php
$str = "<p>Today I went to the zoo and did this and that..</p><p>Well today I didn't do anything interesting...</p><p>Today I played a new game...</p>";
echo htmlspecialchars($str), '<hr>';
$str = preg_replace('%<p>(.*?zoo.*?)</p>%si', '<h2>$1</h2>', $str);
echo htmlspecialchars($str);
?> 
</pre>

 

Depending on the volume of the data, this may not be the most efficient approach.

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.