删除字符串中紧跟前两个字母的字母和空格

发布于 2024-11-17 20:53:52 字数 294 浏览 6 评论 0原文

我正在尝试使用 PHP 的 preg_replace() 替换前两个字母和空格之后的所有字母和空格。这是我这样做的失败尝试:

echo preg_replace('/^[a-zA-Z]{2}([a-zA-Z ])*.*$/i','','FALL 2012');
//expected output is "FA2012", but it outputs nothing

我只是想替换括号中的部分 ([a-zA-Z ]) ..我猜我做得不对只需更换该部分即可。

I'm trying to replace all the letters and spaces after the first two, using PHP's preg_replace(). Here is my failed attempt at doing so:

echo preg_replace('/^[a-zA-Z]{2}([a-zA-Z ])*.*$/i','','FALL 2012');
//expected output is "FA2012", but it outputs nothing

I'm just trying to replace the part in parentheses ([a-zA-Z ]) .. I'm guessing I'm not doing it right to just replace that part.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

寄意 2024-11-24 20:53:52

您要求它替换整个字符串。使用 lookbehind 来匹配前两个字符。

echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');

顺便说一下,i 修饰符意味着它不区分大小写,因此您不需要同时匹配大写和小写字符。

You're asking it to replace the entire string. Use a lookbehind to match the first two characters instead.

echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');

By the way, the i modifier means it's case insensitive, so you don't need to match both uppercase and lowercase characters.

清旖 2024-11-24 20:53:52

在这种情况下,您可以使用 (?<=lookbehind);但是,在某些其他情况下,您可能会发现 \K 转义更合适。它的作用是将应用程序传递的起始偏移值重置为主题中的当前位置,从而有效地转储当前匹配中迄今为止消耗的字符串部分。例如:

preg_replace('^[a-z]{2}\K[a-z ]*/i', '', 'FALL 2012')

现在仅替换 [az ]* 匹配的子字符串。

In this case you can get away with a (?<=lookbehind); however, in certain other cases you may find the \K escape to be more suitable. What it does is reset the start offset value passed by the application to the current position in the subject, effectively dumping the portion of the string that was consumed thus far in the current match. For example:

preg_replace('^[a-z]{2}\K[a-z ]*/i', '', 'FALL 2012')

Now only the substring matched by [a-z ]* is substituted.

暗地喜欢 2024-11-24 20:53:52

末尾的 /i 使其不区分大小写。 (?<=regex) 表示在当前位置之前查找后跟 2 个字母的行开头。

echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');

The /i at the end makes it case-insensitive. The (?<=regex) means look immediately before the current position for the beginning of the line followed by 2 letters.

echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');
冷心人i 2024-11-24 20:53:52

您的意思是用空白('')替换整个匹配项。您想在要保留的部分加上括号,然后替换为 $1$2,它等于第一个 ($1) 和第二个 ($2) 中的内容一组括号。

preg_replace("/^([a-z]{2})[a-z\s]*(.*)$/i", '$1$2', $string);

you are saying to replace the entire match with blank (''). You want to put the parenthesis around the parts you want to keep and then replace with $1$2 which is equal to what is in the first ($1) and second ($2) set of parenthesis.

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