Skip to content
Advertisement

Regular expression matching for entire string

I’m very new to PHP. I need to check whether a given string has characters from a given set, say {a, b, c}. So, I am trying regular expressions. "(abc)+" should do the trick.

However, looking at the manual entries for preg_match and associated functions, I noticed that these functions perform sub-string matching instead of matching the entire string with the regex rule.

I’m sure there is a simple way to do this. Basically, I need a binary answer whether or not the entire string matches the rule. How can I do it?

Advertisement

Answer

You can create your character class by using square brackets. So [abc] would match any of the characters inside the class (the brackets).

To get a series of them, you need a quantifier. You already used the + that means one or more. If you also want to allow the empty string, you can use the * meaning zero or more.

To ensure that you are checking the complete string you need anchors. ^ would match the start of the string and $ the end of the string.

^[abc]+$

This regex would match if the complete string consists only of abc and has at least one character.

You can test regexes online e.g. on Regexr. You can see this regex here and of course modify it.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement