question concerning preg_replace
-
hi all
i’ve gotten into regular expressions recently, read lots of tutorials and got my hands dirty trying to figure out how to properly replace text using a plugin. i would like to know if there’s a more elegant way to do the following.
i want to insert an image tag right before a specified string, but only if that string appears inside a particular tag. for example:
<p class="foo">this is an example</p>
i want to add an image tag right before the word “example”, but only when the word “example” is inside a class=”foo” paragraph. after many trials and errors, i’ve come up with the following function which is called through an add_filter (for the sake of simplicity, i call the image tag in this example <img>):
$string equals the_content in this example
function testing($string) { $pattern = '/<p class=\"foo\">(.*?)(example)(.*?)<\/p>/i'; $replace = '<p class="foo">\1<img>\2\3</p>'; $string = preg_replace($pattern,$replace,$string); return $string; }
since this is newbie stuff, i’d like to know if i’m (wrongly) reinventing the wheel or if i’ve come to the right place.
thanks.
- The topic ‘question concerning preg_replace’ is closed to new replies.