2011-05-13 57 views
0

如何找到給定字符串中兩個子字符串值之間的距離?例如,如果我有這個詞很棒,我想找到「我」之間的距離(相距一個空格)。謝謝你的幫助。2個子字符串之間的距離

+2

有你嘗試過什麼? – 2011-05-13 22:59:58

+0

如果在字符串中有三個i,你想要兩個鄰居中最小的,最大的,最左邊到最右邊的節點? – 2011-05-13 23:01:45

回答

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]; 
} 
+0

+1 OP可能會將'$ pos1 + 1'更改爲'$ pos1 + strlen($ needle)'以使用長度超過一個字符的針。還應該將'$ distance'遞減爲'6-4 = 2',並且OP需要'1',即中間的一個字符。 – webbiedave 2011-05-13 23:12:49

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";