regular expressions for url parser
Asked Answered
F

5

5
<?php

    $string = 'user34567';

            if(preg_match('/user(^[0-9]{1,8}+$)/', $string)){
                echo 1;
            }

?>

I want to check if the string have the word user follows by number that can be 8 symbols max.

Fargone answered 12/6, 2012 at 15:21 Comment(0)
G
11

You're very close actually:

if(preg_match('/^user[0-9]{1,8}$/', $string)){

The anchor for "must match at start of string" should be all the way in front, followed by the "user" literal; then you specify the character set [0-9] and multiplier {1,8}. Finally, you end off with the "must match at end of string" anchor.

A few comments on your original expression:

  1. The ^ matches the start of a string, so writing it anywhere else inside this expression but the beginning will not yield the expected results
  2. The + is a multiplier; {1,8} is one too, but only one multiplier can be used after an expression
  3. Unless you're intending to use the numbers that you found in the expression, you don't need parentheses.

Btw, instead of [0-9] you could also use \d. It's an automatic character group that shortens the regular expression, though this particular one doesn't save all too many characters ;-)

Gherardo answered 12/6, 2012 at 15:23 Comment(0)
H
4

By using ^ and $, you are only matching when the pattern is the only thing on the line. Is that what you want? If so, use the following:

preg_match( '/^user[0-9]{1,8}[^0-9]$/' , $string );

If you want to find this pattern anywhere in a line, I would try:

preg_match( '/user[0-9]{1,8}[^0-9]/' , $string );

As always, you should use a reference tool like RegexPal to do your regular expression testing in isolation.

Hookah answered 12/6, 2012 at 15:28 Comment(0)
V
2

You were close, here is your regex : /^user[0-9]{1,8}$/

Volva answered 12/6, 2012 at 15:23 Comment(0)
F
1

try the following regex instead:

/^user([0-9]{1,8})$/

Farmhand answered 12/6, 2012 at 15:23 Comment(0)
L
1

Use this regex:

/^user\d{1,8}$/
Longhand answered 12/6, 2012 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.