删除字符串中紧跟前两个字母的字母和空格
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您要求它替换整个字符串。使用 lookbehind 来匹配前两个字符。
顺便说一下,
i
修饰符意味着它不区分大小写,因此您不需要同时匹配大写和小写字符。You're asking it to replace the entire string. Use a lookbehind to match the first two characters instead.
By the way, the
i
modifier means it's case insensitive, so you don't need to match both uppercase and lowercase characters.在这种情况下,您可以使用
(?<=lookbehind)
;但是,在某些其他情况下,您可能会发现 \K 转义更合适。它的作用是将应用程序传递的起始偏移值重置为主题中的当前位置,从而有效地转储当前匹配中迄今为止消耗的字符串部分。例如:现在仅替换
[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:Now only the substring matched by
[a-z ]*
is substituted.末尾的
/i
使其不区分大小写。(?<=regex)
表示在当前位置之前查找后跟 2 个字母的行开头。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.您的意思是用空白('')替换整个匹配项。您想在要保留的部分加上括号,然后替换为 $1$2,它等于第一个 (
$1
) 和第二个 ($2
) 中的内容一组括号。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.