正则表达式用两边的空格替换给定的单词或根本不替换 [英] regex to replace a given word with space at either side or not at all

查看:35
本文介绍了正则表达式用两边的空格替换给定的单词或根本不替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP 中的一些代码从搜索引擎中获取引用数据,为我提供用户输入的查询.

I am working with some code in PHP that grabs the referrer data from a search engine, giving me the query that the user entered.

然后我想从该字符串中删除某些停用词(如果存在).但是,单词的两端可能有也可能没有空格.

I would then like to remove certain stop words from that string if they exist. However, the word may or may not have a space at either end.

比如我一直用str_replace删除一个词如下:

For example, I have been using str_replace to remove a word as follows:

$keywords = str_replace("for", "", $keywords);
$keywords = str_replace("sale", "", $keywords);

但如果 $keywords 值是婴儿配方",它会将其更改为婴儿穆拉" - 删除for"部分.

but if the $keywords value is "baby formula" it will change it to "baby mula" - removing the "for" part.

无需为for"和for"创建进一步的 str_replace 帐户 - 是否有我可以使用的 preg_replace 类型命令来删除给定的单词,如果它的两端有空格?

Without having to create further str_replace's that account for " for" and "for " - is there a preg_replace type command I could use that would remove the given word if it is found with a space at either end?

我的想法是将所有停用词放入一个数组中并以这种方式单步执行,我怀疑 preg_replace 将比单步执行多个 str_replace 行更快.

My idea would be to put all of the stop words into an array and step through them that way and I suspect that a preg_replace is going to be quicker than stepping through multiple str_replace lines.

更新:感谢你们使用以下组合解决了:

UPDATE: Solved thanks to you guys using the following combination:

$keywords = "...";
$stopwords = array("for","each");
foreach($stopwords as $stopWord)
{
    $keywords = preg_replace("/(\b)$stopWord(\b)/", "", $keywords);   
}

推荐答案

$keywords = "...";
$stopWords = array("for","sale");
foreach($stopWords as $stopWord){
    $keywords = preg_replace("/(\b)$stopWord(\b)/", "", $keywords);
}

这篇关于正则表达式用两边的空格替换给定的单词或根本不替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆