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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10778318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:02:25  来源:igfitidea点击:

Test if a string is regex

phpregexpreg-match

提问by Hosh Sadiq

Is there a good way of test if a string is a regex or normal string in PHP?

有没有一种很好的方法来测试字符串是 PHP 中的正则表达式还是普通字符串?

Ideally I want to write a function to run a string through, that returns true or false.

理想情况下,我想编写一个函数来运行一个字符串,该函数返回 true 或 false。

I had a look at preg_last_error():

我看了看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 0both times.

显然第一个不是错误,第二个是。但是两次都preg_last_error()返回int 0

Any ideas?

有任何想法吗?

采纳答案by ThiefMaster

The only easy way to test if a regex is valid in PHP is to use it and check if a warning is thrown.

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

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.

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

回答by Niet the Dark Absol

The simplest way to test if a string is a regex is:

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

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

This will tell you if a string has a good chance of being intended to be as a regex. However there are many string that would pass that check but fail being a regex. Unescaped slashes in the middle, unknown modifiers at the end, mismatched parentheses etc. could all cause problems.

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

The reason preg_last_errorreturned 0 is because the "invalid regex" is not:

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

  • PREG_INTERNAL_ERROR (an internal error)
  • PREG_BACKTRACK_LIMIT_ERROR (excessively forcing backtracking)
  • PREG_RECURSION_LIMIT_ERROR (excessively recursing)
  • PREG_BAD_UTF8_ERROR (badly formatted UTF-8)
  • PREG_BAD_UTF8_OFFSET_ERROR (offset to the middle of a UTF-8 character)
  • PREG_INTERNAL_ERROR(内部错误)
  • PREG_BACKTRACK_LIMIT_ERROR(过度强制回溯)
  • PREG_RECURSION_LIMIT_ERROR(过度递归)
  • PREG_BAD_UTF8_ERROR(UTF-8 格式错误)
  • PREG_BAD_UTF8_OFFSET_ERROR(偏移到 UTF-8 字符的中间)

回答by ya_dimon

Here is a good answer how to:

这是一个很好的答案如何:

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

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

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

回答by Ben

Why not just use...another regex? Three lines, no @kludges or anything:

为什么不使用...另一个正则表达式?三行,没有@杂乱无章或任何东西:

// 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");

Or, in function form, even more pretty:

或者,在函数形式中,甚至更漂亮:

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


This doesn't test validity; but it looks like the question is Is there a good way of test if a string is a regex or normal string in PHP?and it does do that.

这不会测试有效性;但看起来问题是Is there a good way of test if a string is a regex or normal string in PHP?,它确实做到了。