Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

properly escape URL slashes in regex

Tags:

regex

php

I need help escaping slashes in a pattern which searches a URL path. I'm trying to check if a path contains any numbers in the path after /orders/ like this:

$str = '/admin/store/orders/20284?width...';

if ( preg_match ( '/orders/([0-9]+)/', $str, $matches ) )
{
    print_r($matches);
}

However, I am not able to escape the slashes properly. Can anybody help? Thank you.

like image 496
qqmisko Avatar asked Nov 27 '15 19:11

qqmisko


1 Answers

Escaping is done with backslashes (\/). But the slash character to delimit regular expressions can be any character:

if ( preg_match ( '~orders/([0-9]+)~', $str, $matches ) )

Will work without escaping.

like image 197
miken32 Avatar answered Nov 15 '22 09:11

miken32