Based on comments to the answer, this is a preferable solution, as it will return nothing when there is no match to the $to
string instead of the entire string as the original solution did.
function getStringBetween($str,$from,$to){
if (preg_match("/$from([^$from]+)$to/", $str, $matches))
return $matches[1];
else
return '';
}
$str = 'SIM UMTS ITALIA 35GB BLACK';
echo getStringBetween($str, ' ', 'GB') . "
";
$str2 = 'SIM UMTS ITALIA IPHONE 2 MEGAPIXEL';
echo getStringBetween($str2, ' ', 'GB') . "
";
$str3 = 'SIM UMTS ITALIA 15.5" BLACK';
echo getStringBetween($str3, ' ', '"') . "
";
Output:
35
15.5
Demo on 3v4l.org
Original Answer
It is probably easier to use preg_replace
instead, looking for some digits or a period before a "
and removing all other characters from the string e.g.
$str = 'SIM UMTS ITALIA 15.5" BLACK';
echo preg_replace('/^.*?(\d+(\.\d+)?)".*$/', '$1', $str);
Output:
15.5
More generically (if $from
is a character):
function getStringBetween($str,$from,$to){
return preg_replace("/^.*$from([^$from]+)$to.*$/", '$1', $str);
}
Demo on 3v4l.org