具有特定长度的任何字符串的正则表达式模式

时间:2022-05-31 21:40:05

I want to build pattern for preg_match that will match any string with length 1 - 40 chars. I found this:

我想为preg_match构建模式,该模式将匹配长度为1 - 40个字符的任何字符串。我找到了这个:

^[^<\x09]{1,40}\Z

But with that one I recieve this error message:

但有了那个,我收到这个错误信息:

function.preg-match]: Unknown modifier '<' in ....

Any suggestion ?

有什么建议吗?

2 个解决方案

#1


10  

/^.{1,40}$/ should match any string that's 1 to 40 characters long.

/^.{1,40}$/应该匹配任何长度为1到40个字符的字符串。

What it does is that it takes the ., which matches everything, and repeats it 1 to 40 times ({1,40}). The ^ and $ are anchors at the beginning and end of the string.

它所做的是它需要匹配所有内容的。,并重复1至40次({1,40})。 ^和$是字符串开头和结尾的锚点。

#2


7  

If you don't care what the characters are, you don't need regex. Use strlen to test the length of a string:

如果你不在乎字符是什么,你就不需要正则表达式。使用strlen来测试字符串的长度:

if ((strlen($yourString) <= 40) && (strlen($yourString) >= 1)) {

}

This will be far faster than booting up the PCRE engine.

这比启动PCRE引擎要快得多。


Addendum: if your string may contain multi-byte characters (e.g. é), you should use mb_strlen, which takes these characters into consideration.

附录:如果您的字符串可能包含多字节字符(例如é),则应使用mb_strlen,它会考虑这些字符。

#1


10  

/^.{1,40}$/ should match any string that's 1 to 40 characters long.

/^.{1,40}$/应该匹配任何长度为1到40个字符的字符串。

What it does is that it takes the ., which matches everything, and repeats it 1 to 40 times ({1,40}). The ^ and $ are anchors at the beginning and end of the string.

它所做的是它需要匹配所有内容的。,并重复1至40次({1,40})。 ^和$是字符串开头和结尾的锚点。

#2


7  

If you don't care what the characters are, you don't need regex. Use strlen to test the length of a string:

如果你不在乎字符是什么,你就不需要正则表达式。使用strlen来测试字符串的长度:

if ((strlen($yourString) <= 40) && (strlen($yourString) >= 1)) {

}

This will be far faster than booting up the PCRE engine.

这比启动PCRE引擎要快得多。


Addendum: if your string may contain multi-byte characters (e.g. é), you should use mb_strlen, which takes these characters into consideration.

附录:如果您的字符串可能包含多字节字符(例如é),则应使用mb_strlen,它会考虑这些字符。