slawrence10
slawrence10

Reputation: 202

Using preg_match to check URL with "wildcard"

So I want to check if a string is in the format:

checkout/00/payment

where 00 can be any number.

I tried using preg_match to do this, but it didn't work out:

if(preg_match('/checkout/ [0-9] /payment/', $url, $matches)){
         echo 'hello';  
}

Further I want it to fail if the string has any characters after the word 'payment' e.g checkout/00/payment/more

Upvotes: 1

Views: 1584

Answers (3)

uınbɐɥs
uınbɐɥs

Reputation: 7351

Your regex has extra spaces in it, and [0-9] will only match one digit.

Also, if you start and end your regex with /, you can't use / inside it, unless you escape it with a backslash (\/).

I've used ~ instead for this.

if(preg_match('~checkout/([0-9]+)/payment$~', $url, $matches)) {
    echo 'Matched! (' . $matches[1] . ')';
}

This will match one or more digits.

Demo: codepad.viper-7.com/qoKI5G

Upvotes: 1

Jordan Mack
Jordan Mack

Reputation: 8733

The following regex below now matches as you would expect. Notice that I surrounded the digits with parenthesis. This captures the number in $matches so you can use it later.

<?php
header('Content-Type: text/plain');

foreach(array(0,5,10,99) as $i)
{
    $num = str_pad($i, 2, '0', STR_PAD_LEFT);
    $url = 'checkout/'.$num.'/payment';

    if(preg_match('/checkout\/([0-9]+)\/payment/i', $url, $matches))
    {
        echo 'url: "'.$url."\"\n";
        echo 'hello: '.$matches[1]."\n";
        print_r($matches);
    }

    echo "\n\n";
}
?>

This code produces the following output:

url: "checkout/00/payment"
hello: 00
Array
(
    [0] => checkout/00/payment
    [1] => 00
)


url: "checkout/05/payment"
hello: 05
Array
(
    [0] => checkout/05/payment
    [1] => 05
)


url: "checkout/10/payment"
hello: 10
Array
(
    [0] => checkout/10/payment
    [1] => 10
)


url: "checkout/99/payment"
hello: 99
Array
(
    [0] => checkout/99/payment
    [1] => 99
)

preg_match manual page

preg_match_all manual page

PCRE regex syntax manual page

Possible modifiers in regex patterns

Upvotes: 4

alexn
alexn

Reputation: 58982

[0-9] matches only a single digit. If you want to match exactly two digits, append {2}: [0-9]{2}.

Upvotes: 2

Related Questions