PHP preg_replace帮助请,删除多个单词和单个字符的所有实例


php preg_replace help please, remove all instances of multiple words and single chars

我有以下内容

$search_keywords = preg_replace('/'s{1,}(and's*)*/', ' ', $search_keywords);

从$search_keywords

中删除单词"and"和任何额外的空格

但是当我尝试添加其他要删除的单词时,比如

$search_keywords = preg_replace('/'s{1,}(and|with's*)*/', ' ', $search_keywords);

任何字符串,它将删除单词,但不删除额外的空格,但它会删除单词"with"和空格,如果在字符串中找到?

我还尝试了下面的

$search_keywords = preg_replace('/'s{1,}(and's*)(with's*)*/', ' ', $search_keywords);

,但这只适用于单词"and",而不会删除单词"with",如果存在的话。

所以我要做的是从我的变量中删除单词"and"answers"with"的所有实例,并删除可能留下的任何额外的空格。

我还想从字符串中删除所有出现在自己ie中的单个字符:"A","I","£","?" Etc "任何"单独出现的字符(由空格包围)

所以我们说我的字符串是:"你想要牛排和薯条配芦笋酱吗?"

我希望能够有以下返回:"do want steak chips asparagus sauce"

因此,它删除了带有、的单词,以及单个字符ua?

希望这是有意义的?

感谢任何帮助由于

你可以使用:

$search_keywords = preg_replace('/'s+('S('s|$)|((and|with)'s*('S's+)?)+)/i', ' ', $search_keywords);

您的正则表达式(and|with's*)将允许在with之后有0个或多个空格。

演示工作

try this:

$search_keywords = preg_replace(array('/'s{1,}(and's*)*/','/'s{1,}(with's*)*/'), ' ', $search_keywords);