在有结束索引限制的字符串中查找子字符串最后一次出现的位置


find the position of last occurrence of sub string in a string with limit of ending index

我有一个类似的字符串

$string="abc @def @xyz $ @def @xyz";

现在我想得到$之前最后一次出现@的索引。

目前我正在使用

strrpos($string,'@');

strrpos的第三个参数将是起始索引,我们能给出结束索引吗?

使用strrpos可以获得最后一次出现。更多关于函数.strrpos

出于您的目的,您需要使用$分解字符串,并为分解数组的第一个index启动strrpos的应用程序。

试试这个:

$string="abc @def @xyz $ @def @xyz";
$strArr = explode('$', $string);
$pos = strrpos($strArr[0], "@");
if ($pos === false) { // note: three equal signs
    echo 'Not Found!';
}else
    echo $pos; //Output 9 this case

另一种选择:-

$string="abc @def @xyz $ @def @xyz";
$pos = strrpos($string, '@', -strrpos($string, '$')); 
if($pos === false){ 
    echo 'Not Found!';
}else{
    echo $pos; // 9
}

注意:-负号将返回$sign之前最后一个'@'的索引。