Support » Plugins and Hacks » question concerning preg_replace

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.


Viewing 1 replies (of 1 total)
  • There are few things in my computing life that have had me wishing for a noose as much as regular expressions… :D

    I see nothing off in the regex (it’ll work, and that holds some importance here). As long as you keep in mind you are making a few assumptions as to the pattern to be matched, specifically double quotes enclosing “foo” and not single or (Heaven forfend!) no quotes at all, and your class being placed at the end of the <p> tag.

Viewing 1 replies (of 1 total)
  • The topic ‘question concerning preg_replace’ is closed to new replies.