简体   繁体   中英

PHP regexp for a valid regexp pattern

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

In the back office of my application, the administrator define the data type and he can define a pattern as a regexp. For example /^[AZ][a-zA-Z]+[az]$/ 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.

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

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM