There is a construction that parses the /start command in a telegram bot with parameters.

 $command = '/start 123'; $regex = '/(\/start\s)(\d+)/'; if(preg_match($regex, $command, $match)) { echo 'start with parameter detected'; } 

How do I specify in a regular expression that (\d+) an optional parameter? What would you catch like /start or /start 123 ?

  • To use a lazy quantifier ( ? ) After a group with a number, a regular expression can have the following form: \/start\s(\d+)? - Let's say Pie

1 answer 1

Use a quantifier ? in the following way:

 $regex = '/(\/start)(?:\s(\d+))?/'; 

See the demo online .

  • (\/start) - Exciting disguise number 1: /start
  • (?: - the beginning of an optional unsubstantiated subplot (because after it immediately stands the quantifier ? )
    • \s - whitespace
    • (\d+) - Addictive Mask # 2: 1 or more digits
  • )? - The end of the optional unsuspecting trap, 1 or 0 repetitions.