preg_match:无需重复/不匹配 [英] preg_match: nothing to repeat / no match

查看:98
本文介绍了preg_match:无需重复/不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个:if(!preg_match('/^+[0-9]$/', '+1234567'))

并且我得到:

<块引用>

警告:preg_match()[function.preg-match]:编译失败:在偏移量 1 处无需重复

有什么想法吗?


更新:现在使用:if(!preg_match('/^\+[0-9]$/', '+1234567'))

并且我没有匹配.

有什么想法吗?

解决方案

+ 是一个特殊字符,表示前一个字符的 1 个或多个,并且不转义它就是将它应用到插入符号.用 \ 转义它,它将匹配一个文字加号.

if(!preg_match('/^\+[0-9]$/', '+1234567'))

不匹配的原因是您指定了 0-9 中的 1 位数字,并用 $ 指定了字符串的结尾.您需要将其设为可变数量的数字.

if(!preg_match('/^\+[0-9]+$/', '+1234567')) {

更短的版本:

if(!preg_match('/^\+\d+$/', '+1234567')) {

I am using this: if(!preg_match('/^+[0-9]$/', '+1234567'))

and am getting:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 1

any ideas why?


update: Now using this: if(!preg_match('/^\+[0-9]$/', '+1234567'))

and am getting no match.

any ideas why?

解决方案

+ is a special character that indicates 1 or more of the previous character, and by not escaping it you are applying it to the caret. escape it with \ and it will match a literal plus sign.

if(!preg_match('/^\+[0-9]$/', '+1234567'))

EDIT:

The reason why it didn't match is because you specified 1 digit from 0-9 and the end of the string with $. You need to make it a variable amount of digits.

if(!preg_match('/^\+[0-9]+$/', '+1234567')) {

Shorter version:

if(!preg_match('/^\+\d+$/', '+1234567')) {

这篇关于preg_match:无需重复/不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆