测试字符串是否为正则表达式 [英] Test if a string is regex
问题描述
是否有一种很好的方法来测试字符串是PHP中的正则表达式还是普通字符串?
理想情况下,我想编写一个函数来运行一个字符串,该字符串返回true或false.
我看了preg_last_error()
:
<?php
preg_match('/[a-z]/', 'test');
var_dump(preg_last_error());
preg_match('invalid regex', 'test');
var_dump(preg_last_error());
?>
显然第一个不是错误,第二个是错误.但是preg_last_error()
两次都返回int 0
.
有什么想法吗?
测试正则表达式在PHP中是否有效的唯一简单方法是使用它并检查是否引发警告.
ini_set('track_errors', 'on');
$php_errormsg = '';
@preg_match('/[blah/', '');
if($php_errormsg) echo 'regex is invalid';
但是,使用任意用户输入作为正则表达式是一个坏主意.以前,PCRE引擎中存在安全漏洞(缓冲区溢出=>远程执行代码),并且可能会创建特制的长正则表达式,这些正则表达式需要大量的CPU/内存才能编译/执行.
Is there a good way of test if a string is a regex or normal string in PHP?
Ideally I want to write a function to run a string through, that returns true or false.
I had a look at preg_last_error()
:
<?php
preg_match('/[a-z]/', 'test');
var_dump(preg_last_error());
preg_match('invalid regex', 'test');
var_dump(preg_last_error());
?>
Where obviously first one is not an error, and second one is. But preg_last_error()
returns int 0
both times.
Any ideas?
The only easy way to test if a regex is valid in PHP is to use it and check if a warning is thrown.
ini_set('track_errors', 'on');
$php_errormsg = '';
@preg_match('/[blah/', '');
if($php_errormsg) echo 'regex is invalid';
However, using arbitrary user input as a regex is a bad idea. There were security holes (buffer overflow => remote code execution) in the PCRE engine before and it might be possible to create specially crafted long regexes which require lots of cpu/memory to compile/execute.
这篇关于测试字符串是否为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!