2016-01-10 52 views
0

我的字符串来自我的数组。我如何用字符串中的其他单词替换单词

$a="Root|Electronics|Categories|Mobiles & Accessories|Smartphones & Basic Mobiles|Smartphones|"; 

$b="Root|Electronics|Categories|Mobiles & Accessories|Smartphones & Basic Mobiles|Smartphones & Mobiles"; 

$c="Root|Electronics|Categories|Mobiles & Accessories|Smartphones & Basic Mobiles|Smart Android mobile"; 

在上面的例子Root|Electronics|Categories|Mobiles & Accessories|Smartphones & Basic Mobiles|是常见的,在字符串中的话可能会改变。

在这种情况下,我试图从数组中找到一个常见的匹配,并将此字符串替换为不同的字符串。

对于实施例Root|Electronics|Categories|Mobiles & Accessories|Smartphones & Basic Mobiles%是第一公共匹配的字符串,我将取代使用不同的字符串等Mobiles

为了实现这个功能,我可以使用哪个php函数,或者可能有其他建议吗?

谢谢!

+0

你想要处理什么,一个字符串或每个字符串的数组分开? – RomanPerekhrest

回答

0

要找到共同的部分,你可以使用该功能从这里开始:

https://gist.github.com/chrisbloom7/1021218

您需要将字符串添加到一个数组,然后使用此代码示例:

<?php 
function longest_common_substring($words) 
{ 
    $words = array_map('strtolower', array_map('trim', $words)); 
    $sort_by_strlen = create_function('$a, $b', 'if (strlen($a) == strlen($b)) { return strcmp($a, $b); } return (strlen($a) < strlen($b)) ? -1 : 1;'); 
    usort($words, $sort_by_strlen); 
    // We have to assume that each string has something in common with the first 
    // string (post sort), we just need to figure out what the longest common 
    // string is. If any string DOES NOT have something in common with the first 
    // string, return false. 
    $longest_common_substring = array(); 
    $shortest_string = str_split(array_shift($words)); 
    while (sizeof($shortest_string)) { 
    array_unshift($longest_common_substring, ''); 
    foreach ($shortest_string as $ci => $char) { 
     foreach ($words as $wi => $word) { 
     if (!strstr($word, $longest_common_substring[0] . $char)) { 
      // No match 
      break 2; 
     } // if 
     } // foreach 
     // we found the current char in each word, so add it to the first longest_common_substring element, 
     // then start checking again using the next char as well 
     $longest_common_substring[0].= $char; 
    } // foreach 
    // We've finished looping through the entire shortest_string. 
    // Remove the first char and start all over. Do this until there are no more 
    // chars to search on. 
    array_shift($shortest_string); 
    } 
    // If we made it here then we've run through everything 
    usort($longest_common_substring, $sort_by_strlen); 
    return array_pop($longest_common_substring); 
} 

用法:

$array = array(
    'PTT757LP4', 
    'PTT757A', 
    'PCT757B', 
    'PCT757LP4EV' 
); 
echo longest_common_substring($array); 
// => T757 
相关问题