开发者

PHP regexp for a valid regexp pattern

开发者 https://www.devze.com 2023-03-18 11:49 出处:网络
Is there a regexp to check if a string is a valid php regexp ? In the back office of my application, t开发者_如何学编程he administrator define the data type and he can define a pattern as a regexp. F

Is there a regexp to check if a string is a valid php regexp ?

In the back office of my application, t开发者_如何学编程he administrator define the data type and he can define a pattern as a regexp. For example /^[A-Z][a-zA-Z]+[a-z]$/ and in the front office, i use this pattern for validate user entries. In my code i use the PHP preg_match function

preg_match($pattern, $user_entries); 

the first argument must be a valid PHP regexp, how can i be sure that $pattern is a valid regexp since it a user entrie in my back office.

Any idea ?


Execute it and catch any warnings.

$track_errors = ini_get('track_errors');
ini_set('track_errors', 'on');
$php_errormsg = '';
@preg_match($regex, 'dummy');
$error = $php_errormsg;
ini_set('track_errors', $track_errors);
if($error) {
    // do something. $error contains the PHP warning thrown by the regex
}

If you just want to know if the regex fails or not you can simply use preg_match($regex, 'dummy') === false - that won't give you an error message though.


As a work-around, you could just try and use the regex and see if an error occurs:

function is_regex($pattern)
{
  return @preg_match($pattern, "") !== false;
}

The function preg_match() returns false on error, and int when executing without error.

Background: I don't know if regular expressions themselves form a regular grammar, i.e. whether it's even possible in principle to verify a regex with a regex. The generic approach is to start parsing and checking if an error occurs, which is what the workaround does.


Technically, any expression can be a valid regular expression...

So, the validity of a regular expression will depend on the rules you want to respect.

I would:

  1. Identify the rules your regex must do
  2. Use a preg_match of your own, or some combination of substr to validate the pattern


You could use T-Regx library:

<?php
if (pattern('invalid {{')->valid()) {

https://t-regx.com/docs/is-valid

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号