Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

php - Test if a string is regex

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

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

I had a look at 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 0 both times.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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_error returned 0 is because the "invalid regex" is not:

  • 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...