Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match error: Compilation failed: missing terminating ] for character class

Tags:

php

preg-match

I've got a series of .txt files that I'm reading in a for loop. And I've placed a token in some of the text files in the form [widget_]

So, the entire contents of the text file might be [widget_search] for example. And another text file might contain the content [widget_recent-posts]. Others might just have html formatted text and not have the token at all.

In the for loop, I'm doing a preg_match to see if the text file is one in which the contents matches my token pattern. And if a match, I'm executing some conditional code.

However, I'm getting an error when I run a trace test to see if there's a match.

The error is:

Warning: preg_match() [function.preg-match]: Compilation failed: missing terminating ] for character class at offset 8 in C:\xampplite\htdocs\test\wp-content\plugins\widget-test\widget-test.php on line 227

And here's the code at line 227:

if (preg_match("/[widget_/i",$widget_text)) {//do something}
like image 838
Scott B Avatar asked Mar 25 '11 14:03

Scott B


2 Answers

You should escape the [ character like this:

if (preg_match("/\[widget_/i",$widget_text)) { // do something }
like image 167
Imi Borbas Avatar answered Nov 15 '22 03:11

Imi Borbas


it much cleaner to use preg_quote like this:

if (preg_match(preg_quote("/[widget_/i"),$widget_text)) {//do something}
like image 35
Amaynut Avatar answered Nov 15 '22 02:11

Amaynut