March 31st, 2006

PHP - parse a string between two strings

This is a handy little function to strip out a string between two specified pieces of text. This could be used to parse XML text, bbCode, or any other delimited code/text for that matter.

function get_string_between($string, $start, $end){
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);   
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
}

$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");

echo $parsed; // (result = dog)
 

14 Responses to ' PHP - parse a string between two strings '

Subscribe to comments with RSS or TrackBack to ' PHP - parse a string between two strings '.

  1. Bashar said,

    on September 20th, 2006 at 7:51 am

    Thanks for this fine piece of work, I was exactly searching for this.

  2. bcb206 said,

    on November 13th, 2006 at 8:03 pm

    This is a life saver!

  3. Slick said,

    on December 15th, 2006 at 9:05 am

    This is a nice little function that I'm using to parse data from emails.

  4. Alex said,

    on December 30th, 2006 at 9:12 am

    It´s a nice function, thanks!

  5. thanks said,

    on January 19th, 2007 at 1:16 pm

    solved it perfectly. thanks.

  6. Justin Cook said,

    on January 19th, 2007 at 1:29 pm

    Glad it helped. You can always consider the $2 donation as mentioned above ;)

  7. Brian G said,

    on January 27th, 2007 at 8:04 pm

    Great script…though, what if the string contains multiple instances of the same tag…a bold for example?

  8. Justin Cook said,

    on January 28th, 2007 at 11:12 am

    It will just parse the first instance. In which case, just add a third, optional parameter to indicate the starting character search position (int)

  9. Haris N H said,

    on February 9th, 2007 at 12:50 am

    Greate script.It helps me a lot.

  10. George Arkouzis said,

    on May 25th, 2007 at 12:16 pm

    Hi-I was wondering how it would be made to parse this string> "dog+cat+mouse+fish"
    so that the result would be
    "dogcatmousefish"
    Thanks in advance.

  11. Justin Cook said,

    on May 25th, 2007 at 12:25 pm

    I think you'd have to use eregi for that

  12. peter said,

    on May 26th, 2007 at 10:00 am

    str_replace("+","","dog+cat+mouse+fish") = "dogcatmousefish"

  13. Pimm said,

    on July 14th, 2007 at 8:46 am

    Life saver.

  14. sidsevensix said,

    on November 9th, 2007 at 10:11 pm

    whoop! tanks!

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image