preg_replace字符串读取问题

时间:2013-03-01 08:05:28

标签: php

在我的情况下,我只是想从 $ commonWords 数组中的 $ input 中删除字符串。

$input = "perg-replace my string perge replace";

function removeCommonWords($input){  
  $commonWords = array('my','perge');
  return preg_replace('/\b('.implode('|',$commonWords).')\b/','',$input);
}

我预期的结果是:

perg-replace string replace

但是,我从上面得到的结果是:

-replace string replace”

如何告诉perg_replace阅读“ perg-replace ”只有一个单词?

更新

以下代码适用于我:

return preg_replace('/(?<![-\'"])\b('.implode('|',$commonWords).')\b(?![-'"])i','',$input);

4 个答案:

答案 0 :(得分:1)

试试这个......?

function removeCommonWords($input) {
  $commonWords = array('my','perge');
  return implode(' ', array_filter(explode(' ', $input), function($word) use ($commonWords) {
    return !in_array($word, $commonWords);
  }));
}

答案 1 :(得分:0)

试试这个:

// your string.
$str = "perg-replace my string perge replace";

// list of keywords that need to be removed.
$keywords = array('my','perge');

// iterate through the list.
foreach($keywords as $keyword)
{
    $str = preg_replace("/($keyword)/i","",$str);
}

echo $str;

答案 2 :(得分:0)

试试这个,

$input = "perg-replace my string perge replace";
function removeCommonWords($input){  
  $commonWords = array('/my/','/perge/');
  return preg_replace($commonWords,'',$input);
}
echo removeCommonWords($input);

答案 3 :(得分:0)

$input = "perg-replace my string perge replace";

function removeCommonWords($input){  
  $commonWords = array('my','perge');
  return preg_replace('/\b('.implode('|',$commonWords).')\b/','',$input);
}

echo removeCommonWords($input);