How can I find the distance between two substrings values in a given string? For example, if I have the word terrific, and I wanted to find the distance between the "i"s (1 space apart). Thanks for your help.
There are so many options that you could handle, but this is where to start.
$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;
}
}
EDIT
or
$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];
}
Here are a few methods with comments inline:
// 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) . "
";
// 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) . "
";