For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > October 2006 > Syntax check for regex









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Syntax check for regex
Thomas Mlynarczyk

2006-10-30, 7:02 pm

Hi,

Is there a way to check if a string contains a syntactically valid regex?
The only idea that comes to my mind is - using a regex. But I'm afraid such
a regex would be horribly complex. Is there an easier way?

Greetings,
Thomas


Rik

2006-10-30, 7:02 pm

Thomas Mlynarczyk wrote:
> Hi,
>
> Is there a way to check if a string contains a syntactically valid
> regex? The only idea that comes to my mind is - using a regex. But
> I'm afraid such a regex would be horribly complex. Is there an easier
> way?


Well, you could try to run the regex, and capture an error.

$display = ini_set('display_errors',false);
$report = error_reporting(0);
$result = @preg_match($pattern,'');
error_reporting($report);
ini_set('display_errors',$display);
$valid = ($result !== false);

Allthough, throwing Exceptions might be wiser here. I haven't yet worked
with them though.
--
Grtz,

Rik Wasmus


Thomas Mlynarczyk

2006-10-30, 7:03 pm

Also sprach Rik:

> Well, you could try to run the regex, and capture an error.


> $display = ini_set('display_errors',false);
> $report = error_reporting(0);
> $result = @preg_match($pattern,'');
> error_reporting($report);
> ini_set('display_errors',$display);
> $valid = ($result !== false);


Thanks for this suggestion. But if I'm not wrong, the @ operator temporarily
sets error_reporting to 0 anyway, so the second and forth line are not
necessary. Still, I was hoping there was a more "elegant" way to do this.

> Allthough, throwing Exceptions might be wiser here. I haven't yet
> worked with them though.


Yes, I think you are right. However, my first tests with exceptions have
shown that an exception occurs only if it is deliberately thrown using a
throw statement. In other words: an error (like an invalid regex) occurring
in a try-block would simply trigger the normal error handling and not throw
an exception.

Greetings,
Thomas


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com