使用 str_replace...
一个简单的方法是使用字符串替换 http://php.net/str_replace or 字符串替换 http://php.net/str_replace,它可以采用一系列“针”(要搜索的东西)、相应的替换项和一系列“干草堆”(要操作的东西)。
$haystacks=array(
"The quick brown fox",
"jumps over the ",
"lazy dog"
);
$needles=array(
"the", "lazy", "quick"
);
$result=str_ireplace($needles, "", $haystacks);
var_dump($result);
这会产生
array(3) {
[0]=>
string(11) " brown fox"
[1]=>
string(12) "jumps over "
[2]=>
string(4) " dog"
}
顺便说一句,清理留下的尾随空格的快速方法是使用数组映射 http://php.net/array_map打电话trim http://php.net/trim对于每个元素
$result=array_map("trim", $result);
使用 str_replace 的缺点是它会替换找到的匹配项within单词,而不仅仅是整个单词。为了解决这个问题,我们可以使用正则表达式......
使用 preg_replace
一种方法使用预替换 http://php.net/preg_replace看起来与上面非常相似,但针是正则表达式,我们使用 \b 在匹配的开始和结束处检查“单词边界”
$haystacks=array(
"For we shall use fortran to",
"fortify the general theme",
"of this torrent of nonsense"
);
$needles=array(
'/\bfor\b/i',
'/\bthe\b/i',
'/\bto\b/i',
'/\bof\b/i'
);
$result=preg_replace($needles, "", $haystacks);