首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用字符串中的其他单词替换单词?

如何用字符串中的其他单词替换单词?
EN

Stack Overflow用户
提问于 2016-01-10 09:45:37
回答 1查看 46关注 0票数 0

我的字符串来自我的数组,就像。

代码语言:javascript
复制
$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函数,或者您可以建议其他方法吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-10 11:47:03

要找到常见的部分,您可以在这里使用该函数:

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

您需要将字符串添加到数组中,然后使用以下代码:

代码语言:javascript
复制
<?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);
}

用法:

代码语言:javascript
复制
$array = array(
  'PTT757LP4',
  'PTT757A',
  'PCT757B',
  'PCT757LP4EV'
);
echo longest_common_substring($array);
// => T757
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34704044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档