How to get a substring between two strings in PHP? How to get a substring between two strings in PHP? php php

How to get a substring between two strings in PHP?


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)


Regular expressions is the way to go:

$str = 'before-str-after';if (preg_match('/before-(.*?)-after/', $str, $match) == 1) {    echo $match[1];}

onlinePhp


function getBetween($string, $start = "", $end = ""){    if (strpos($string, $start)) { // required if $start not exist in $string        $startCharCount = strpos($string, $start) + strlen($start);        $firstSubStr = substr($string, $startCharCount, strlen($string));        $endCharCount = strpos($firstSubStr, $end);        if ($endCharCount == 0) {            $endCharCount = strlen($firstSubStr);        }        return substr($firstSubStr, 0, $endCharCount);    } else {        return '';    }}

Sample use:

echo getBetween("abc","a","c"); // returns: 'b'echo getBetween("hello","h","o"); // returns: 'ell'echo getBetween("World","a","r"); // returns: ''