Search code examples
phppreg-matchphp-5.3

How to grab string between two keywords in PHP


Not sure if this has been answered before - how can I grab string between two keywords?

For instance the string between a 'story' and a '?',

http://mywebsie.com/hello/blog/story/archieve/2012/5/?page=1    
http://mywebsie.com/blog/story/archieve/2012/4/?page=1
http://mywebsie.com/blog/story/archieve/2012/?page=4

I just want,

story/archieve/2012/5/
story/archieve/2012/4/
story/archieve/2012/

EDIT:

If I use parse_url,

$string = parse_url('http://mywebsie.com/blog/story/archieve/2012/4/?page=1');
echo $string_uri['path'];

I get,

/blog/story/archieve/2012/4/

but I don't want to include 'blog/'


Solution

  • If it is safe to assume that the substrings you are looking for occur exactly once in the input string:

    function getInBetween($string, $from, $to) {
        $fromAt = strpos($string, $from);
        $fromTo = strpos($string, $to);
    
        // if the upper limit is found before the lower
        if($fromTo < $fromAt) return false;
    
        // if the lower limit is not found, include everything from 0th
        // you may modify this to just return false
        if($fromAt === false) $fromAt = 0;
    
        // if the upper limit is not found, include everything up to the end of string
        if($fromTo === false) $fromTo = strlen($string);
    
        return substr($string, $fromAt, $fromTo - $fromAt);
    }
    
    echo getInBetween("http://mywebsie.com/hello/blog/story/archieve/2012/5/?page=1", "story", '?'); // story/archieve/2012/5/