user3315579
user3315579

Reputation:

Regex expression to mach one of many strings in php

I am totally new to regex , I want to match if the value is any one of the following

cs,ch,es,ee,it,me

Till now I have tried

if (preg_match("/^[cs|ch|es|ee|it|me]{2}$/",$val))
    echo "true";
else
    echo "false";

Its working fine for true cases but also returns true for reverse of them like sc,hc etc. Also it will be really helpful if you refer some good source/books to learn it for PHP.

Upvotes: 0

Views: 58

Answers (4)

user2533777
user2533777

Reputation:

You need to use () insteadof []

/^(cs|ch|es|ee|it|me)$/

Note: While using parentheses do not use {2}

So your Final code is:

if (preg_match("/^(cs|ch|es|ee|it|me)$/",$val))
    echo "true";
else
    echo "false";

TO learn regex for php I will suggest this book its a good one for quick refere or refer this question for more.

Upvotes: 0

aelor
aelor

Reputation: 11116

do you know what [] does ?

lets take an example [abcdef]

it will match any of the letters mentioned in the square brackets, suppose you are providing : ^[cs|ch|es|ee|it|me]{2}$

it will match a single character in the list cs|heitm you can add a single letter howsoever times you want but it will match only once.

so it will match any word of two letters as you have mentioned starting with the letters cs|heitm

so it will match cs hs |s etc.

hope you understand it :)

the corrected regex should be

/^(cs|ch|es|ee|it|me)$/

this will match for exact literal words rather than letters.

Upvotes: 0

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

You must use the grouping delimiters (parentheses). The character class delimiters (square brackets) are used for matching ranges of characters.

/^(cs|ch|es|ee|it|me)$/

If you only use the regular expressions to match something (and not capture anything) then you can use the (?:) grouping.

/^(?:cs|ch|es|ee|it|me)$/

One of the better websites for learning regular expressions is regular-expressions.info.

Upvotes: 0

Sabuj Hassan
Sabuj Hassan

Reputation: 39395

Remove the character class [] from your regex and wrap them using (). Also remove the {2} as its not necessary anymore.

if (preg_match("/^(cs|ch|es|ee|it|me)$/",$val))

And this will do for you.

Upvotes: 2

Related Questions