ivan ursul
ivan ursul

Reputation: 1

Regex in php preg_match function

I have a regex pattern

<?php 
if(preg_match("/shop[0-9]/", '/shop43')){
    echo "YES";
}
else
{
    echo "NO";
}
 ?>

It is working, but when i write

if(preg_match("/shop[0-9]/", '/shop43d')){
    echo "YES";
}

it is working too.The problem is that i need to have ony digits after word "shop",for example shop1,shop2,...,shop123 What I need to change in my pattern?) I would be very thankful if somebody could give me a link with some examples of my problem in regex.Thank you :)

Upvotes: 0

Views: 102

Answers (1)

Engineer
Engineer

Reputation: 48793

Try this pattern instead:

/^\/shop[0-9]+$/

You can simply use \d instead of [0-9]:

/^\/shop\d+$/

Explanation:

  • As / used for indicating start/end of expression you have to escape it(to not indicate the end of the expression) -> \/.

  • ^ anchor matches at the start of the string the regex pattern is applied to.

  • $ anchor matches at the end of the string the regex pattern is applied to.

  • + repeats the previous item once or more.

See more info about reg-exps here.

Upvotes: 2

Related Questions