查找偏移量之前最后出现的空格字符


Find last occurrence of a whitespace character before an offset?

假设我有一个字符串"快速的棕色狐狸",我想找到索引 13 上或之前出现的空格字符:

01234567890123456789
The quick brown fox
         ^

我该怎么做?我想对's使用反向正则表达式搜索,但我认为 PHP 不支持在偏移量之前向后搜索。有没有其他方法可以有效地做到这一点?

$string='the quick brown fox';
$ind=13;
function findWS($string,$ind)
{
   $string=substr($string,0,$ind+1);   
   preg_match('/'s*[^'s]+$/',$string,$match,PREG_OFFSET_CAPTURE );
   if(isset($match[0][1])) return $match[0][1]; else return -1; 
}
$v=findWS($string,$ind);
echo $v;

我认为只要$pattern只匹配一个字符,这就可以工作:

function rePosRev($subject, $pattern, $offset=null) {
    if($offset === null) $offset = strlen($subject);
    $search_str = strrev(substr($subject, 0, $offset));
    if(preg_match($pattern, $search_str, $m, PREG_OFFSET_CAPTURE)) {
        return $offset - $m[0][1] - 1;
    }
    return false;
}
echo rePosRev("The quick brown fox", '~'s~', 13); // 9

艾德酮