WordPress.org

Ready to get started?Download WordPress

Forums

question concerning preg_replace (2 posts)

  1. morgentau
    Member
    Posted 6 years ago #

    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.

  2. Kafkaesqui

    Posted 6 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.