如何在php中使用preg_match?

时间:2015-12-16 16:54:59

标签: php html forms validation preg-match

我想创建表单验证,并且我想确保用户不会在文本框中输入任何危险代码,因此我想使用getWritableDatabase来执行此操作。 我不喜欢用户输入的是(某些东西而不是a-z中的单词,来自A-Z的单词和数字)。 现在我如何在这里使用preg_match

2 个答案:

答案 0 :(得分:5)

这个正则表达式只允许使用字母和数字。

/^[A-Z\d]+$/i

用于preg_match

if(preg_match('/^[A-Z\d]+$/i', $string)) {
      echo 'Good';
} else {
     echo 'Bad';
}

Regex101演示:https://regex101.com/r/wH4uQ3/1

^$需要整个字符串匹配(它们是锚点)。 []是一个字符类,意味着允许任何内部字符。 +表示前面的一个或多个字符/组(这称为量词)。 A-Z是字符类理解为字母a-z的范围。 \d是一个数字。 /是分隔符,用于说明正则表达式的开始和结束位置。 i是一个修饰符,使正则表达式不区分大小写(可以删除它并添加a-z,因此也允许使用小写字母。)

PHP演示:https://eval.in/486282

注意PHP演示失败,因为不允许使用空格。要允许空格在字符类中添加\h\ss包含\h,因此不需要两者; \h用于水平空格。)

答案 1 :(得分:-1)

这是一个简单的例子:

您可以在http://php.net/manual/en/function.preg-match.php

查看更多信息

您也可以执行此操作:AmericanizeFunction

$("html").html("
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content='initial-scale=1, minimum-scale=1, width=device-width'>
<title>Error 404 (Not Allowed)!!</title>
<style>*{margin:0;padding:0}
html,code{font:15px/22px arial,sans-serif}
html{background:#fff;color:#222;padding:15px}
body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}
* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}
p{margin:11px 0 22px;overflow:hidden}
ins{color:#777;text-decoration:none}
a img{border:0}
@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}
#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}
@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}
@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}
#logo{display:inline-block;height:54px;width:150px}
</style>
<a href=//www.google.com/>
<span id=logo aria-label=Google>
</span>
</a>
<p>
<b>404.</b>
<ins>That’s an error.</ins>
<p>The requested URL <code>/404</code> was not found on this server.  <ins>That’s all we know.</ins>
<form method='get' action='http://www.google.com/search'>
 <input placeholder='google 404 edition ' type='text' name='q' size='31' maxlength='Infinity' value='' />
 <input type='submit' value='Search' />
</form>
");