Php 两个子串之间的距离
如何找到给定字符串中两个子字符串值之间的距离?例如,如果我有单词“很棒”,我想找出“I”之间的距离(间隔1个空格)。谢谢你的帮助。有很多选择,你可以处理,但这是开始 编辑 或Php 两个子串之间的距离,php,substring,Php,Substring,如何找到给定字符串中两个子字符串值之间的距离?例如,如果我有单词“很棒”,我想找出“I”之间的距离(间隔1个空格)。谢谢你的帮助。有很多选择,你可以处理,但这是开始 编辑 或 以下是一些内嵌注释的方法: // We take our string $mystring = "terrific"; // Then the first character we want to look for $mychar1 = "i"; $mychar2 = "i"; // Now we get the p
以下是一些内嵌注释的方法:
// 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";
你试过什么吗?如果字符串中有三个i,你想让相邻的两个i之间的最小值、最大值、从最左到最右的距离吗?+1 OP可能会将
$pos1+1
更改为$pos1+strlen($pinder)
以使用长度超过一个字符的指针。还应将$distance
减为6-4=2
和OP-wants1
,即介于两者之间的一个字符。
$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];
}
// 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";