【发布时间】:2023-03-10 06:58:01
【问题描述】:
我试图在两个字符串/字符之间获取一个字符串。比如我想得到test=和;之间的字符串“1”:
这是我的工作功能:
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
但我的问题是,如果我必须在cool= 之间获取字符串?我无法使用该功能获得它,因为分号 ; 不在末尾。它需要是动态的。我不知道我需要的字符串是否在给定字符串的最后一部分。
我可以对仍然能够在cool= 之间获取字符串的函数做些什么?调用函数时,我还必须将分号作为第三个参数。
【问题讨论】:
标签: php string function substr strpos