2016-01-10 50 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 
相關問題