测试字符串是否为正则表达式

问题描述 投票:0回答:4

有没有好的方法来测试 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 regex preg-match
4个回答
19
投票

测试字符串是否为正则表达式的最简单方法是:

if( preg_match("/^\/.+\/[a-z]*$/i",$regex))

这将告诉您字符串是否有很好的机会被用作正则表达式。然而,有许多字符串可以通过该检查,但无法成为正则表达式。中间未转义的斜杠、末尾未知的修饰符、不匹配的括号等都可能会导致问题。

preg_last_error
返回0的原因是因为“无效的正则表达式”不是:

  • PREG_INTERNAL_ERROR(内部错误)
  • PREG_BACKTRACK_LIMIT_ERROR(过度强制回溯)
  • PREG_RECURSION_LIMIT_ERROR(过度递归)
  • PREG_BAD_UTF8_ERROR(UTF-8 格式错误)
  • PREG_BAD_UTF8_OFFSET_ERROR(UTF-8 字符中间的偏移量)

17
投票

这里有一个很好的答案:

https://stackoverflow.com/a/12941133/2519073

if(@preg_match($your_pattern, '') === false){
    //pattern is broken
}else{
    //pattern is real
}

10
投票

测试正则表达式在 PHP 中是否有效的唯一简单方法是使用它并检查是否抛出警告。

ini_set('track_errors', 'on');
$php_errormsg = '';
@preg_match('/[blah/', '');
if($php_errormsg) echo 'regex is invalid';

但是,使用任意用户输入作为正则表达式是一个坏主意。 PCRE 引擎之前存在安全漏洞(缓冲区溢出 => 远程代码执行),并且可能会创建特制的长正则表达式,这需要大量的 cpu/内存来编译/执行。


9
投票

为什么不直接使用...另一个正则表达式?三行,没有

@
拼凑或任何东西:

// Test this string
$str = "/^[A-Za-z ]+$/";

// Compare it to a regex pattern that simulates any regex
$regex = "/^\/[\s\S]+\/$/";

// Will it blend?
echo (preg_match($regex, $str) ? "TRUE" : "FALSE");

或者,以函数形式,更漂亮:

public static function isRegex($str0) {
    $regex = "/^\/[\s\S]+\/$/";
    return preg_match($regex, $str0);
}

这并不测试有效性;但看起来问题是

Is there a good way of test if a string is a regex or normal string in PHP?
并且它确实做到了。

© www.soinside.com 2019 - 2024. All rights reserved.