JeffVader
JeffVader

Reputation: 702

preg_match matching specific characters = { } [] *

if (preg_match('/[^a-zA-Z]+/', $test4, $matches))

This will match any non alphanumeric character. I only want a match on { } [ ] * = regardless of order and any other characters between them. Can this be done?

I have tried \=, \[, \], \{, \}, \* but that didn't seem to help?

I have a string that may or may not contain the characters listed. I would like to use preg_match to find out if the string does contain any of those characters, regardless of order or position in string.

Upvotes: 0

Views: 5084

Answers (2)

mbarlocker
mbarlocker

Reputation: 1386

Those characters, with the exception of the equals sign, are control characters in regular expressions. You will have to treat them differently.

I would recommend reading the PCRE Regex Syntax

To get what you're looking for, try this.

preg_match('/\[(.*)\]/', $test4, $square_matches);
preg_match('/\{(.*)\}/', $test4, $curly_matches);

// or, if this is your approach (it's hard to tell from your description)
preg_match('/([\[\{=\*](.*)[\]\}=\*])/', $test4, $matches);
preg_match('/([\[\{=\*](.*?)[\]\}=\*])/', $test4, $matches); //non-greedy

Upvotes: 0

Barmar
Barmar

Reputation: 781028

Does this do what you want?

if (preg_match ('/[{}\[\]=*]+/', $test4, $matches))

If you want to find all the matches rather than just the first, you should use preg_match_all.

Upvotes: 2

Related Questions