问题描述
我在preg_match()函数中遇到了这个奇怪的错误:
I'm getting this odd error in the preg_match() function:
警告:preg_match():编译失败:字符类在偏移量54处范围混乱
Warning: preg_match(): Compilation failed: range out of order in character class at offset 54
引起此问题的行是:
preg_match("/<!--GSM\sPER\sNUMBER\s-\s$gsmNumber\s-\sSTART-->(.*)<!--GSM\sPER\sNUMBER\s-\s$gsmNumber\s-\sEND-->/s", $fileData, $matches);
此正则表达式的作用是解析HTML文件,仅提取以下部分:
What this regular expression does is parse an HTML file, extracting only the part between:
<!--GSM PER NUMBER - 5550101 - START-->
和:
<!--GSM PER NUMBER - 5550101 - END-->
您是否暗示可能导致此错误的原因?
Do you have a hint about what could be causing this error?
推荐答案
如果$gsmNumber
包含方括号,反斜杠或其他各种特殊字符,则可能会触发此错误.如果可能的话,您可能需要验证这一点,以确保它实际上是此点之前的数字.
If $gsmNumber
contains a square bracket, backslash or various other special characters it might trigger this error. If that's possible, you might want to validate that to make sure it actually is a number before this point.
编辑2016:
有一个PHP函数可以在正则表达式中转义特殊字符: preg_quote()
.
There exists a PHP function that can escape special characters inside regular expressions: preg_quote()
.
像这样使用它:
preg_match(
'/<!--GSM\sPER\sNUMBER\s-\s' .
preg_quote($gsmNumber, '/') . '\s-\sSTART-->(.*)<!--GSM\sPER\sNUMBER\s-\s' .
preg_quote($gsmNumber, '/') . '\s-\sEND-->/s', $fileData, $matches);
很显然,在这种情况下,因为您使用了两次相同的字符串,所以可以先将带引号的版本分配给变量,然后再使用它.
Obviously in this case because you've used the same string twice you could assign the quoted version to a variable first and re-use that.
这篇关于字符类中的范围乱序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!