从字符串中删除单词

时间:2014-09-26 07:52:44

标签: php string-matching

我有一个包含公司名称的csv文件。我想将它与我的数据库匹配。为了获得更清晰,更接近的比赛,我想要消除一些公司后缀,如'inc','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有关。但我无法弄清楚如何解决这个问题。

4 个答案:

答案 0 :(得分:1)

试试这个:

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

foreach ($wordlist as $word) {
    $string =str_replace($word, '', $string);
}
echo $string;

OR

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

这将输出为'公司'......

如果您希望“合并”结果,请将“我”设为小...而不是运行上面的代码(第一个)......

答案 1 :(得分:0)

enter image description here您可以使用此

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

运行此代码here

答案 2 :(得分:0)

试试这个。它可能涉及类型杂耍,但会有你想要的结果

    $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);

答案 3 :(得分:0)

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

$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;