How to get a substring between two strings in PHP?

Nadjib Mami picture Nadjib Mami · Apr 17, 2011 · Viewed 298k times · Source

I need a function that returns the substring between two words (or two characters). I'm wondering whether there is a php function that achieves that. I do not want to think about regex (well, I could do one but really don't think it's the best way to go). Thinking of strpos and substr functions. Here's an example:

$string = "foo I wanna a cake foo";

We call the function: $substring = getInnerSubstring($string,"foo");
It returns: " I wanna a cake ".

Thanks in advance.

Update: Well, till now, I can just get a substring beteen two words in just one string, do you permit to let me go a bit farther and ask if I can extend the use of getInnerSubstring($str,$delim) to get any strings that are between delim value, example:

$string =" foo I like php foo, but foo I also like asp foo, foo I feel hero  foo";

I get an array like {"I like php", "I also like asp", "I feel hero"}.

Answer

Alejandro García Iglesias picture Alejandro García Iglesias · Mar 22, 2012

If the strings are different (ie: [foo] & [/foo]), take a look at this post from Justin Cook. I copy his code below:

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)