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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.