计算从字符串位置 x 到字符串位置 y 的字符数


Count characters from string position x to string position y

如何找到字符串与另一个字符串的位置之间有多少个字符

例如,字符串可能是:棕色狐狸

如何找到"r"和"f"之间有多少个字符?

提前致谢

$r_pos = strpos($str, 'r');
$distance = strpos($str, 'f', $r_pos) - $r_pos - 1;
echo $distance;
$str = "brown fox";
strpos($str,'f') - strpos($str,'r');

使用 strpos( 或 stripos 进行不区分大小写的搜索(,获取 "r" 的位置和 "f" 的位置。然后,减去两者。

$phrase = "brown fox";
echo stripos( $phrase, "f" ) - stripos( $phrase, "r" );

如果您的句子可以在"r"之前包含"f",则可以通过将"r"的位置作为第三个参数来传递"f"的偏移量stripos

$r = stripos( $phrase, "r" );
$f = stripos( $phrase, "f", $r );
echo $f - $r;