我可以在php中使用javascript正则表达式吗? [英] Can I use javascript regular expression in php as it is
问题描述
我在javascript中使用正则表达式,并希望使用相同的正则表达式进行服务器端验证。我是否需要对其进行修改以使其兼容或者按原样运行。
I am using a regular expression in javascript and want to do server side validation as well with the same regular expression. Do i need to modify it to make it compatible or will it run as it is.
如何使用PHP常规表达式。请提供一个小例子。
How to use PHP regular expresion. Please provide a small example.
提前致谢
编辑
用于电子邮件验证
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
电话无需验证
var pattern = new RegExp(/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/);
推荐答案
您应该使用以下功能之一 preg_match 或 preg_match_all 。运气好的话,你不需要修改你的正则表达式。
PHP正则表达式使用经典的Perl正则表达式,所以匹配看起来像
preg_match_all('/([a-zA-Z0-9] +)/',$ myStringToBeTested, $ results);
You should use one of the following functions preg_match or preg_match_all. And with a bit of luck you shouldn't need to modify your regex.
PHP regex uses the classic Perl regex, so a match would look like
preg_match_all('/([a-zA-Z0-9]+)/', $myStringToBeTested, $results);
稍后编辑:
$string="test@mail.com";
if(preg_match('/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/', $string))
echo "matches!";
else
echo "doesn't match!";
享受!
这篇关于我可以在php中使用javascript正则表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!