7

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}

2 Answers 2

17

You should escape the [ character like this:

if (preg_match("/\[widget_/i",$widget_text)) { // do something }
Sign up to request clarification or add additional context in comments.

3 Comments

I figured it was something simple. Would you advice that I change the format of my token to avoid having to escape the character or other potential problems?
There's nothing wrong with using [] - it's just that they happen to be metacharacters in regexes. Use any delimiter you want, just be aware that there could potentially be some other function/module that uses that alternate character as a metacharacter as well.
Thanks for the quick help and exlano. +1
1

it much cleaner to use preg_quote like this:

if (preg_match(preg_quote("/[widget_/i"),$widget_text)) {//do something}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.