-2
function get_string_between($string, $start, $end, $preo) {
    if (strpos($string,$start)===FALSE) {    
        return $preo;
    } else {
        if (strlen($string)!==0) {
            $ini   = strpos($string, $start);        
            $pre   = substr($string,0,$ini);
            $ini   += strlen($start);
            $len   = strpos($string, $end, $ini) - $ini;
            $part  = chr(substr($string, $ini, $len));
            $preo .= $pre;
            $preo .= $part;
            $newString = substr($string, strlen($pre) + strlen(substr($string,$len)) + strlen($start) + strlen($end), strlen($string)-strlen($pre));
            get_string_between($newString,$start,$end,$preo);
        } 
    }  
}

$rr = get_string_between("vishalOo59oOOo59oO", 'Oo', 'oO', '');
var_dump($rr);           

The above program is returning null.

Zhorov
  • 28,486
  • 6
  • 27
  • 52
strike5
  • 1
  • 2

2 Answers2

0

You don't return anything in the else block. So if the condition is false then the returned value would be null.

Return from your recursive call in the else block:

return get_string_between($newString,$start,$end,$preo);
David
  • 208,112
  • 36
  • 198
  • 279
  • can u write the solution? – strike5 Jun 16 '20 at 11:13
  • @strike5: When you apply the change suggested by this answer, does the code not work in some additional way? The line of code shown in this answer is the only line that was modified. All you need to do is add `return` before the recursive call to `get_string_between` in the `else` block. Currently your function doesn't return a value, so the solution is to return that value. – David Jun 16 '20 at 11:15
0

I think you dont need to create such typical function, if you want to find a string between 2 substring like this:

$str = 'vishalOo59oOOo59oO';
preg_match('/Oo(.*?)oO/', $str, $match);
print_r($match);

Output:

Array
(
    [0] => Oo59oO
    [1] => 59
)
59

Do let me know if you any issue arises

Edit:

Also in your statement you are not returning anything in else statement you need to throwback something to get.

function get_string_between($string, $start, $end, $preo) {
    if (strpos($string,$start)===FALSE) {    
        return $preo;
    } else {
        if (strlen($string)!==0) {
            $ini   = strpos($string, $start);        
            $pre   = substr($string,0,$ini);
            $ini   += strlen($start);
            $len   = strpos($string, $end, $ini) - $ini;
            $part  = chr(substr($string, $ini, $len));
            $preo .= $pre;
            $preo .= $part;
            $newString = substr($string, strlen($pre) + strlen(substr($string,$len)) + strlen($start) + strlen($end), strlen($string)-strlen($pre));
            return get_string_between($newString,$start,$end,$preo);
        } 
    }  
}
Jaymin
  • 1,643
  • 1
  • 18
  • 39