Yes, there are. If you use RegEx, you can just as well use one regex, like this. The length can be skipped too, by using start or string/end of string anchors.
if ($colour && preg_match("/^#([0-9a-fA-F]){3}(([0-9a-fA-F]){3})?$/", $colour)
{
}
I think the 'check for value' can be skipped to, but that might make sense as an optimization.
if (preg_match("/^#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6}$/", $colour)) {
Let your regular expressions check the length of the string by adding the ^ and $ signs signaling start/end of a string, and combining your regular expressions:
if (preg_match("/^#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6}$/", $colour)) {
发布评论
评论(5)
是的,有。如果你使用正则表达式,你也可以使用一个正则表达式,就像这样。通过使用字符串锚点的开始或字符串/结束符,也可以跳过长度。
我认为可以跳过“检查价值”,但这作为一种优化可能是有意义的。
[编辑]
事实证明这是 RegEx 备忘单上的示例< /a>.
Yes, there are. If you use RegEx, you can just as well use one regex, like this. The length can be skipped too, by using start or string/end of string anchors.
I think the 'check for value' can be skipped to, but that might make sense as an optimization.
[edit]
It turns out to be an example on the RegEx cheat sheet.
让正则表达式通过添加表示字符串开始/结束的 ^ 和 $ 符号并组合正则表达式来检查字符串的长度:
Let your regular expressions check the length of the string by adding the ^ and $ signs signaling start/end of a string, and combining your regular expressions:
对我来说似乎足够了。
seems enough to me.
您可以使用
^
和$
锚定正则表达式,以便隐含长度。我不太了解 php,但在 perl 中,您需要将
$
转义为\$
或使用单引号。You could anchor your regex with
^
and$
so the length is implied.I don't know php that well, but in perl you would need to escape the
$
as\$
or use single quotes instead.您的正则表达式已经指定了字符串的长度,因此如果您设置开始
^
和结束$
边界,则无需检查它:Your regexp already specify stings' lenghts so you do not need to check it if you set start
^
and end$
boundaries: