I'm trying to get a part of my url using PHP preg_match but it's not working. I followed some instructions but no luck.
This is what I have so far.
$url = 'http://chris.mydomain.com/d/3542re6s/somthing.html';
$pattern = '/\/\/(sub1\.)?mydomain.com\/(\d+)($|\/)/';
preg_match($pattern, $url, $matches);
if (count($matches)){
return $matches[2];
}
I also need it to validate for chris, terry and jack only.
UPDATED:
eg: chris.mydomain.com terry.mydomain.com jack.mydomain.com
And I need to get the second query
eg:
chris.mydomain.com/d/3542re6s/somthing.html
would return
3542re6s
Any help is very much appreciated.
Thanks in advance C
Your regular expression is missing the /d/
directory. Also, since the next level contains both numbers and letters, you can't use \d+
to match it. Try this:
$pattern = '#//(?:(?:chris|terry|jack)\.)?mydomain\.com/d/([^/]+)(?|/)#';
DEMO at regex101
PHP demo at ideone
And when you're writing a regular expression to match pathnames, I suggest using a delimiter other than /
so you don't have to escape all the slashes in the regexp; I used #
above.