fishfin Posted August 5, 2008 Share Posted August 5, 2008 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); Quote Link to comment Share on other sites More sharing options...
effigy Posted August 5, 2008 Share Posted August 5, 2008 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.