[英]PHP exact match between input and regex pattern
I'm trying to build a check that reliably evaluates whether the input ($f_username) is a MAC Address via Regex 'cause there are different Syntax it could take. 我正在尝试建立一个检查,以通过Regex可靠地评估输入($ f_username)是否为MAC地址,因为它可能采用不同的语法。 Upon finding a match.
找到匹配项后。 this should be transferred to lowercase without deliminators.
应当将其转换为小写字母而不带限定符。
The function works fine in matching and transforming most input, but will wrongly match longer input... eg 11-22-33-44-55-66-77-88 would be transferred to 11-22-33-44-55-66 and $match is set to true... 该功能可以很好地匹配和转换大多数输入,但是会错误地匹配更长的输入...例如11-22-33-44-55-66-77-88将被传输到11-22-33-44-55- 66并且$ match设置为true ...
This should cause the function to go to the "else branch" as is is not an exact match of the pattern... however it contains a match... does anybody have an idea how to properly match this ? 这应该导致函数转到“ else分支”,因为它不是该模式的精确匹配...但是它包含一个匹配项...有人知道如何正确匹配该模式吗?
Thanks for taking the time to read this and thanks in advance for any answers :) 感谢您抽出宝贵的时间阅读本文,并预先感谢您的任何回答:)
function username_check($f_username) {
global $match;
if (preg_match_all("/([0-9a-fA-F]{2})[^0-9a-fA-F]?([0-9a-fA-F]{2})[^0-9a-fA-F]?([0-9a-fA-F]{2})[^0-9a-fA-F]?([0-9a-fA-F]{2})[^0-9a-fA-F]?([0-9a-fA-F]{2})[^0-9a-fA-F]?([0-9a-fA-F]{2})/", $f_username, $output, PREG_PATTERN_ORDER)) {
for ($i = 1; $i <= 6; $i++) {
$new_username .= strtolower($output[$i][0]);
}
$match = true;
$new_username = "'" . $new_username . "'"; //for later use in SQL-Query
} else {
$match = false;
}
return $new_username;
}
I recommend using the RegEx from this answer , as it ensures a well-formed MAC-address. 我建议从此答案中使用RegEx ,因为它可以确保格式正确的MAC地址。 If you want to add spaces to the list of delimiters, just replace this
[-:]
with this [: -]
. 如果要在定界符列表中添加空格,只需将此
[-:]
替换为[-:]
[: -]
。
You are experiencing the problem you described because you haven't bound your RegEx to the start, or the end of a string. 您遇到的问题是因为您尚未将RegEx绑定到字符串的开头或结尾。 Which means that as long as there's a match somewhere inside the string it's a valid match.
这意味着只要字符串中某处有匹配项,它就是有效匹配项。
To bind it to the start of a string, use ^
just after the opening delimiter. 要将其绑定到字符串的开头,请在开始定界符之后使用
^
。 To bind it at the end of a string, I recommend* using \\z
just before the closing delimiter. 要在字符串末尾绑定它,我建议*在结束定界符之前使用
\\z
。
* Reason I recommend \\z
over $
, in PHP, is because the latter will allow a newline after the match. *之所以建议在PHP中使用
$
不是\\z
,是因为后者在比赛之后将允许换行。 That means that the string "testing\\n"
will match a pattern bound with $
, but not one bound with \\z
. 这意味着字符串
"testing\\n"
将匹配与$
绑定的模式,而不与与\\z
绑定的模式匹配。 Most of the times you really do not want that newline. 大多数时候,您确实不希望使用换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.