user1702396 user1702396 - 5 months ago 15
PHP Question

How to check if a given string is valid Regex?


Possible Duplicate:

Test if a regular expression is a valid one in PHP




<?php

$subject = "PHP is the web scripting language of choice.";
$pattern = 'sssss';

if(preg_match($pattern,$subject))
{
echo 'true';
}
else
{
echo 'false';
}

?>


The above code gives me warning because the string
$pattern
is not a valid regular expression.

If I pass valid regular expression then it works fine.....

How can i check
$pattern
is valid regular expression?

F0G F0G
Answer

You can just wrap preg_match with try catch, and consider result false, if it throws exception.

Anyway, you can take a look at regular expression to detect a valid regular expression.