更正正则表达式以删除单词前后的空格

发布于 2024-11-02 02:08:48 字数 278 浏览 2 评论 0原文

我使用下面的正则表达式字符串来查找在本例中仅紧跟一个空格的单词。我在这里缺少什么?这会删除所有空格,但我需要留下一些空格。我只是想删除紧跟空格的单词,我该怎么做。一个例子是输入。 (一二三)第一次替换应删除“三”,第二次替换应删除“一”,仅留下二。如果我只想要剩下三个,我只会使用第二行代码。我的主要问题是在这里获取正确的正则表达式模式。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

野鹿林 2024-11-09 02:08:48

[Az] 只匹配一个字母 - 而且它也是不正确的,因为您应该声明 [a-zA-Z] 来匹配所有大写和小写字母。

尝试使用:

/\s[a-zA-Z]+/

之后

/[a-zA-Z]+\s/

,您的代码应如下所示:

preg_replace('/\s[a-zA-Z]+/', '', $data);
preg_replace('/[a-zA-Z]+\s/', '', $data);

[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:

/\s[a-zA-Z]+/

and

/[a-zA-Z]+\s/

After that, your code should looks like:

preg_replace('/\s[a-zA-Z]+/', '', $data);
preg_replace('/[a-zA-Z]+\s/', '', $data);
感性不性感 2024-11-09 02:08:48

最大的问题是在你的例子中,“Two”前面还有一个空格。因此,第一次替换将删除“二”和“三”(将 [Az] 更改为 [A-Za-z]+ 后,是)。

我想你想要这样的东西:

/\s[a-z]+(?!\s)/i
/(?<!\s)[a-z]+\s/i

注意添加 + 量词。否则,[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:

/\s[a-z]+(?!\s)/i
/(?<!\s)[a-z]+\s/i

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.

灼痛 2024-11-09 02:08:48

添加 + 可获取 A 和 z 之间的一个或多个字符。

preg_replace('/[A-Za-z]+\s/', '', $data);
preg_replace('/\s[A-Za-z]+/', '', $data);

Add + to get one or more characters between A and z.

preg_replace('/[A-Za-z]+\s/', '', $data);
preg_replace('/\s[A-Za-z]+/', '', $data);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文