简体   繁体   English

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

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

I have the following 我有以下

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

which removes the word "and" and any extra spaces from $search_keywords 从$ search_keywords中删除单词“ and”和任何多余的空格

but when i try and add other words to remove like so 但是当我尝试添加其他单词删除像这样

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

any string with and in it it will remove the word but not the extra space, but it will remove the word "with" and the space if found in the string? 任何带有and的字符串将删除单词,但不会删除多余的空格,但是如果在字符串中找到,它将删除单词“ with”和空格?

i also tried the following 我也尝试了以下

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

but that worked only for the word "and" but didn't remove the word "with" if present. 但这仅适用于“与”一词,但并未删除“与”一词(如果存在)。

so what i am trying to do is remove all instances of the words "and" and "with" from my varible and remove any extra spaces that may leave. 所以我想做的是从我的变量中删除单词“ and”和“ with”的所有实例,并删除所有可能剩余的空格。

Also i'd like to remove all single characters from the string which appear on their own ie: " a "," i "," £ "," ? " etc "any" single char that appears on its own (surrounded by spaces) 我也想从字符串中删除所有单独出现的单个字符,即:“ a”,“ i”,“£”,“?”等“任何”单独出现的单个字符(由空格包围) )

so lets say my string is: "do u want steak and chips with a asparagus sauce?" 所以可以说我的字符串是: “您要牛排和薯条配芦笋酱吗?”

I want to be able to have the following returned: "do want steak chips asparagus sauce" 我希望能够返回以下内容: “想要牛排片芦笋酱”

therefor it has removed the words with and and as well as the single char u , a and ? 为此它已删除的单词以及单字符U,A

hope that makes sence? 希望有道理?

appreciate any help thanks 感谢任何帮助谢谢

You can correct your regex using: 您可以使用以下方式更正您的正则表达式:

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

Your regex (and|with\\s*) will allow 0 or more spaces after with . 您正则表达式(and|with\\s*)将允许后0或多个空格with

Working Demo 工作演示

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM