簡體   English   中英

從字符串中刪除單詞

[英]Remove word from a string

我有一個包含公司名稱的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有關。 但我只是不知道如何解決這個問題。

嘗試這個 :

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

這將輸出為“公司” ...

如果您希望將“ Incorporated”作為結果,請使“ I”很小..然后運行我上面的代碼(第一個)...

在此處輸入圖片說明 你可以用這個

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

在此處運行此代碼

嘗試這個。 它可能在某些時候涉及類型變戲法,但會得到您想要的結果

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

這將適用於數組中任意數量的元素...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM