問題描述:
我有兩個字串,我需要找到它們相交的長度。
讓我們假設這兩個字串都是拉丁 ASCII 和小寫。
這些是預期的結果:
$str1 = "lorem ipsum";
$str2 = "rem";
echo str_intersection($str1, $str2); // Expected result: 3
$str2 = "xzy";
echo str_intersection($str1, $str2); // Expected result: 0
我嘗試解決問題:
我試圖以array_intersect()這種方式使用函式比較字串:
$str_intersection = function(string $str1, string $str2): int {
$arr1 = str_split($str1); // ['l','o','r','e','m',' ','i','p','s','u','m']
$arr2 = str_split($str2); // ['r','e','m']
return count(array_intersect($arr1, $arr2));
};
echo $str_intersection($str1, $str2); // Result: 4 (because of lo*REM* ipsu*M*)
但是這種比較兩個字串的方式是不合適的,因為它比較的是字符的出現,而不是我需要的字串的整個部分。
另外,這樣設計的str_intersection()函式不僅不合適,而且如果我需要比較上千個字串的話,速度也很慢。
示例我計劃如何使用所需的功能:
根據要求,我寫了一個小例子,我打算如何使用字串交集函式:
$strings = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur'];
$needle = 'lo';
$intersections = [];
foreach ($strings as $str) {
$intersections[] = str_intersection($str, $needle);
}
print_r($intersections);
預期結果(交叉點“ highlighted ”為大寫):
Array (
[0] => 1 // LOrem
[1] => 0 // ipsum
[2] => 1 // doLOr
[3] => 0 // sit
[4] => 0 // amet
[5] => 0 // consectetur
)
uj5u.com熱心網友回復:
這是我的嘗試。
function str_intersection($str1, $str2)
{
[$long, $short] = strlen($str1) > strlen($str2) ? [$str1, $str2] : [$str2, $str1];
$shortLength = strlen($short);
for ($length = $shortLength; $length > 0; $length--) {
for ($offset = 0; $offset < $shortLength - 1; $offset ) {
if (strpos($long, substr($short, $offset, $length)) !== false) return $length;
}
}
return 0;
}
$str1 = "lorem ipsum";
$str2 = "rem";
echo str_intersection($str1, $str2) . PHP_EOL; // Expected result: 3
$str2 = "xzy";
echo str_intersection($str1, $str2) . PHP_EOL; // Expected result: 0
這輸出:
3
0
見:https ://3v4l.org/7YW0R#v8.0.25
這個函式首先對輸入字串進行排序,所以我們知道哪一個是最短的。然后它嘗試在較長的字串中找到這個最短字串的最長部分。這不是很有效,誰能改進呢?
uj5u.com熱心網友回復:
比較第一個匹配字符,然后比較直到結束。對于您希望它不區分大小寫的情況,我使用了strtolower()。
$countIntersections = function (string $source, string $snippet): int {
$a = strtolower($source);
$b = strtolower($snippet);
$index = 0;
$lengths = [];
while ($index < strlen($a)) {
$pos = strpos($a, $b[0], $index);
if (false === $pos) break;
$max = strlen($b);
while ($max) {
if (substr($a, $pos, $max) === substr($b, 0, $max)) {
$lengths[] = $max;
break;
}
$max--;
}
$index = $pos 1;
}
return max([0, ...$lengths]);
};
var_dump($countIntersections('Lorem ipsum', 'rem'));
var_dump($countIntersections('Lorem ipsum', 'um'));
var_dump($countIntersections('Lorem ipsum', 'abc'));
輸出
int(3)
int(2)
int(0)
uj5u.com熱心網友回復:
您可以使用 strpos 函式
https://www.php.net/manual/en/function.strpos.php
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531961.html
標籤:php细绳相比路口
