I'm trying to get a string in between two strings/characters. For example, I want to get the string "1" in between test=
and ;
:
Here is my working function:
function getStringInBetween($str, $start, $end){
$str = ' ' . $str;
$ini = strpos($str, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($str, $end, $ini) - $ini;
return substr($str, $ini, $len);
}
$myString = 'ok=0;test=1;cool=2';
echo getStringInBetween('$myString', 'test=', ';'); // returned output: 1
echo getStringInBetween('$myString', 'cool=', ';'); // this doesn't work. This should output 2
But my question is, if I have to get the string in between cool=
? I cannot get it with the function because the semi colon ;
is not at the end. It needs to be dynamic. I don't know if the string I need is in the last part of the given string or not.
What can I do to the function that will still be able to get the string in between cool=
? Also I have to have the semi-colon as the 3rd argument when calling the function.
You can use the explode function to split a string by a token, here use explode(";", $string) to obtain the following array array("ok=0", "test=1", "cool=2")
Then you can loop through the array and do a second call to explode:
foreach(explode(";", $string) as $pair)
{
$array = explode("=", $pair);
$key = $array[0];
$value = $array[1];
//Do something with $key and $value
}
Regarding your function, something like that should do the trick:
function getStringInBetween($str, $start, $end){
$ini = strpos($str, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$endIndex = strpos($str, $end, $ini);
if ($endIndex === false)
return substr($str, $ini);
else
return substr($str, $ini, $endIndex - $ini);
}
Also you should check $ini
against false and not 0 like that : if ($ini === false) return '';