简体   繁体   English

PHP正则表达式,允许字母数字以及连字符和句点

[英]PHP regular expression to allow alphanumerics plus hyphens and periods

I really don't understand regular expressions and was wondering what the following regular expressions do. 我真的不理解正则表达式,并且想知道以下正则表达式的作用。 I want my address and name to accept . 我希望接受我的地址和姓名. , - and alphanumerics. -和字母数字。

Will this work or is there need for improvement? 这项工作还是需要改进? Plus if someone can break down the regular expressions '/^[A-Z0-9 \\'.-]{1,255}$/i' so I can understand every part better. 另外,如果有人可以分解正则表达式'/^[A-Z0-9 \\'.-]{1,255}$/i'那么我可以更好地理解每个部分。

Here is the php code. 这是PHP代码。

if (preg_match ('/^[A-Z0-9 \'.-]{1,255}$/i', $_POST['address'])) {
    $address = mysqli_real_escape_string($mysqli, htmlentities($_POST['address']));
} else {
    echo '<p class="error">Please enter your address!</p>';
}

if (preg_match ('/^[A-Z0-9 \'.-]{1,255}$/i', $_POST['name'])) {
    $name = mysqli_real_escape_string($mysqli, htmlentities($_POST['name']));
} else {
    echo '<p class="error">Please enter your name!</p>';
}

/ : Regex delimiter / :正则表达式分隔符

^ : Anchor the match at the start of the string ^ :将匹配项锚定在字符串的开头

[A-Z0-9 \\'.-] : Match a letter (AZ, no accented characters), a number, a space, an apostrophe, a dot or a dash [A-Z0-9 \\'.-] :匹配字母(AZ,不带重音符号),数字,空格,撇号,点或破折号

{1,255} : between 1 and 255 times. {1,255} :1至255次。

$ : Anchor the match at the end of the string. $ :将匹配项锚定在字符串的末尾。 Together with ^ , this ensures that the entire string must match, and not just a substring. ^一起,这可以确保整个字符串必须匹配,而不仅仅是子字符串。

/ : Regex delimiter / :正则表达式分隔符

i : Make the regex case-insensitive i :使正则表达式不区分大小写

Your pattern basically allowes any combination (between 1 and 255 characters) of the following: AZ, 0-9, space, \\, ', . 您的模式基本上允许以下任意组合(介于1到255个字符之间):AZ,0-9,空格,\\,',.。

Decide for yourself if this is good enough. 自己决定这是否足够好。

As for your pattern: 至于你的模式:

/^[A-Z0-9 \'.-]{1,255}$/i 

The i at the end means it isnt case sensitive 最后的i表示它不区分大小写

/^[A-Z0-9 \'.-]{1,255}$/ 

The slashes denote the beginning and the end of the pattern 斜线表示模式的开始和结束

^[A-Z0-9 \'.-]{1,255}$

The ^ is the beginning and $ is the end of the string you look for ^是您要查找的字符串的开头,$是结尾的字符串

[A-Z0-9 \'.-]{1,255}

This allowes and combination of the characters between the brackets with 1 to 255 repetitions 允许和括弧之间的字符组合以及1到255个重复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM