Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 两个子串之间的距离_Php_Substring - Fatal编程技术网

Php 两个子串之间的距离

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

如何找到给定字符串中两个子字符串值之间的距离?例如,如果我有单词“很棒”,我想找出“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 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-wants
1
,即介于两者之间的一个字符。
$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";