Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expressions for url parser

<?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.

like image 437
Marian Petrov Avatar asked Jun 12 '12 15:06

Marian Petrov


People also ask

Can we apply regular expression on parser?

The Parse Regex operator (also called the extract operator) enables users comfortable with regular expression syntax to extract more complex data from log lines. Parse regex can be used, for example, to extract nested fields.

What is a regular expression URL?

A Regular Expression, REGEX, is a special text string for describing a search pattern. Within Hotjar, you can use Regular Expressions to target pages with Feedback widgets or Surveys, or to determine when Hotjar should start recording a user's session.

Can you parse XML with regex?

XML is not a regular language (that's a technical term) so you will never be able to parse it correctly using a regular expression.

Can you parse regex with regex?

You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML.


1 Answers

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 ;-)

like image 116
Ja͢ck Avatar answered Sep 25 '22 16:09

Ja͢ck