【问题标题】:Remove word from a string从字符串中删除单词
【发布时间】:2014-11-21 04:10:51
【问题描述】:

我有一个包含公司名称的 csv 文件。我想将它与我的数据库进行匹配。为了有一个更干净和更接近的匹配,我正在考虑删除一些公司后缀,如“inc”、“inc”、“inc”。或',公司'。这是我的示例代码:

$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc."," Inc.",", Inc.",", Inc"," Inc");

foreach ($wordlist as &$word) {
    $word = '/\b' . preg_quote($word, '/') . '\b/';
}

$string = preg_replace($wordlist, '', $string);
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;

我的问题是'inc.'不会被删除。我猜它与preq_quote有关。但我就是不知道如何解决这个问题。

【问题讨论】:

    标签: php string-matching


    【解决方案1】:

    这适用于数组中任意数量的元素...

    $string = 'Inc Incorporated inc.';
    $wordlist = array("Inc");
    
    foreach($wordlist as $stripped)
    $string = preg_replace("/\b". preg_quote($stripped,'/') ."(\.|\b)/i", " ", $string) ;
    
    $foo = preg_replace('/\s+/', ' ', $string);
    echo $foo;
    

    【讨论】:

      【解决方案2】:

      你可以用这个

      $string = 'Inc Incorporated inc.';
      $wordlist = array("Inc "," inc.");
      $foo = str_replace($wordlist, '', $string);
      echo $foo;
      

      运行此代码here

      【讨论】:

      • 嗨@Tushar Gupta,它输出'orporated'。它应该得到整个 Incorporated。
      • 我应该告诉你,$wordlist 是由许多后缀组成的。其中之一是'Inc'。所以它仍然会返回“orporated”。
      • @user3360031 请看我已经放置了代码输出的屏幕截图
      【解决方案3】:

      试试这个:

      $string = 'Inc incorporated inc.';
      $wordlist = array("Inc","inc.");
      
      foreach ($wordlist as $word) {
          $string =str_replace($word, '', $string);
      }
      echo $string;
      

      $string = 'Inc Incorporated inc.';
      $wordlist = array("Inc","inc.");
      $string = str_replace($wordlist, '', $string);
      echo $string;
      

      这将输出为“corporated”...

      如果你想要“Incorporated”作为结果,让“I”变小......然后运行我上面的代码(第一个)......

      【讨论】:

      • 那会回显orporated
      • 如果你想“合并”作为结果,把“我”变小......然后运行我上面的代码(第一个)......
      【解决方案4】:

      试试这个。它可能在某些时候涉及类型杂耍,但会产生您想要的结果

          $string = 'Inc Incorporated inc.';
          $wordlist = array('Inc', 'inc.');
      
          $string_array = explode(' ', $string);
      
          foreach($string_array as $k => $a) {
              foreach($wordlist as $b) {
                  if($b == $a){
                      unset($string_array[$k]);
                  }
          }
      
          $string_array = implode('', $string_array);
      

      【讨论】:

      • 这样就完成了。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 2017-03-27
      • 2017-07-17
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多