如何找到给定字符串中两个子串值之间的距离?例如,如果我有一个很棒的词,我想找到“i”之间的距离(相隔1个空格)。谢谢你的帮助。
答案 0 :(得分:1)
$haystack = 'terrific';
$needle = 'i';
$distance = false;
$pos1 = strpos($haystack,$needle);
if ($pos1 !== false) {
$pos2 = strpos($haystack,$needle,$pos1+1);
if ($pos2 !== false) {
$distance = $pos2 - $pos1;
}
}
修改强>
或
$haystack = 'terrific';
$needle = 'i';
$distance = false;
$needlePositions = array_keys(array_intersect(str_split($haystack),array($needle)));
if (count($needlePositions) > 1) {
$distance = $needlePositions[1] - $needlePositions[0];
}
答案 1 :(得分:1)
以下是一些内联注释的方法:
// We take our string
$mystring = "terrific";
// Then the first character we want to look for
$mychar1 = "i";
$mychar2 = "i";
// Now we get the position of the first character
$position1 = strpos( $mystring, $mychar1);
// Now we use the last optional parameter offset to get the next i
// We have to go one beyond the previous position for this to work
// Properly
$position2 = strpos( $mystring, $mychar2, ($position1 + 1) );
// Then we get the distance
echo "Distance is: " . ($position2 - $position1) . "\n";
// We can also use strrpos to find the distance between the first and last i
// if there are more than one
$mystring2 = "terrific sunshine";
$position2 = strrpos( $mystring2, $mychar2);
echo "Distance is: " . ($position2 - $position1) . "\n";
答案 2 :(得分:0)
你可以处理很多选项,但这是从哪里开始的。