如何在PHP中使用正则表达式找到最长的子字符串?

时间:2016-03-14 05:28:18

标签: php arrays regex sequence

我有以下数组:

$array = array("6", "66", "67", "68", "69", "697", "698", "699");  

我有以下字符串:

"69212345", "6209876544", "697986546"  

我想找到一个数组元素,它匹配字符串开头的最长部分,即

  • 表示“69212345”数组值“69”将被选中。

  • 对于“6209876544”,将选择数组值“6”。

  • 表示“697986546”将选择数组值“697”。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

尝试以下解决方案:

$array = array("6", "66", "67", "68", "69", "697", "698", "699");

$str = '697986546';
//get all matched valuew
$new_arr = array_filter($array, function ($val) use ($str) {
    return (strpos($str, $val) !== false);
});

print_r($new_arr);
if ($new_arr) {
//sort data by string length
    usort($new_arr, function ($a, $b) {
        return strlen($b) - strlen($a);
    });
    print_r($new_arr);

    echo "longest value is - " . $new_arr[0];
}

输出:

Array
(
    [0] => 6
    [4] => 69
    [5] => 697
)
Array
(
    [0] => 697
    [1] => 69
    [2] => 6
)
longest value is - 697

答案 1 :(得分:0)

这应该适合你:

只需循环遍历您的数组并检查您的字符串中是否存在strpos()的值,如果加上它的长度超过现在最长的subSequence,则可以重新分配它,例如

$longestSubsequence = "";
foreach($array as $v){

    if(strpos($str, $v) !== FALSE && strlen($v) > strlen($longestSubsequence ))
        $longestSubsequence = $v;

}
echo $longestSubsequence;

答案 2 :(得分:-1)

使用substr():

尝试此解决方案
<?php
$match = "";
$array = array("6", "66", "67", "68", "69", "697", "698", "699");
$strings = array("69212345", "6209876544", "697986546");
for ($i=0; $i < count($strings); $i++) { //loop to get the $string values
  for ($ii=0; $ii < sizeof($array); $ii++) { //loop to get the $array values
    for ($iii=0; $iii < strlen($strings[$i]); $iii++) { //this loop will increment until the end of the string to compare the array if it matches the substr() of $strings
      if (substr($strings[$i], 0, $iii + 1) == $array[$ii]) {
        $match = $array[$ii];
      }
    }
  }
  echo "for \"" . $strings[$i] . "\" array value \"" . $match . "\" will be selected<br>";
}
?>

<强>输出:

for "69212345" array value "69" will be selected
for "6209876544" array value "6" will be selected
for "697986546" array value "697" will be selected