更正正则表达式以删除单词前后的空格
我使用下面的正则表达式字符串来查找在本例中仅紧跟一个空格的单词。我在这里缺少什么?这会删除所有空格,但我需要留下一些空格。我只是想删除紧跟空格的单词,我该怎么做。一个例子是输入。 (一二三)第一次替换应删除“三”,第二次替换应删除“一”,仅留下二。如果我只想要剩下三个,我只会使用第二行代码。我的主要问题是在这里获取正确的正则表达式模式。
preg_replace('/\s[A-z]/', '', $data);
preg_replace('/[A-z]\s/', '', $data);
I'm using the regex string below to look for words that in this case are only immediately followed by one space. What am i missing here? This removes any and all spaces, however i need some left. Im only trying to remove words that are immediately followed by a space, how would i do this. An example would be the input being. (One Two Three) The first replace should remove " Three" and the second replace should remove "One " leaving only Two. If i only wanted Three left i would only use the second line of code. My main issue is getting the correct regex pattern here.
preg_replace('/\s[A-z]/', '', $data);
preg_replace('/[A-z]\s/', '', $data);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
[Az]
只匹配一个字母 - 而且它也是不正确的,因为您应该声明[a-zA-Z]
来匹配所有大写和小写字母。尝试使用:
之后
,您的代码应如下所示:
[A-z]
matches only one letter - and it it incorrect too because you should declare[a-zA-Z]
to match all letters upper- and lowercase.Try with:
and
After that, your code should looks like:
最大的问题是在你的例子中,“Two”前面还有一个空格。因此,第一次替换将删除“二”和“三”(将
[Az]
更改为[A-Za-z]+
后,是)。我想你想要这样的东西:
注意添加
+
量词。否则,[az]
将仅匹配一个字符,因此您的“一二三”示例可能会导致“On w hre”。此外,从技术上来说,[Az] 会导致未定义的行为(并且可能引发异常),因为大写 A 到小写 z 不是有效范围。您需要
[A-Za-z]
或使用[az]
进行不区分大小写的匹配,正如我上面所做的那样。The biggest problem is that in your example, "Two" also has a space in front of it. Therefore, the first replace will remove both " Two" and " Three" (once you've changed the
[A-z]
to[A-Za-z]+
, that is).I think you want something like this:
Note the addition of the
+
quantifier. Without that, the[a-z]
will only match one character, so your "One Two Three" example will probably result in "On w hree".Also,
[A-z]
technically results in undefined behavior (and may throw an exception) since capital A to lowercase z isn't a valid range. You want either[A-Za-z]
or a case-insensitive match using[a-z]
, as I've done above.添加 + 可获取 A 和 z 之间的一个或多个字符。
Add + to get one or more characters between A and z.