[英]PHP preg_match to get part of my url
I'm trying to get a part of my url using PHP preg_match but it's not working.我正在尝试使用 PHP preg_match 获取我的 url 的一部分,但它不起作用。 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.我还需要它来仅验证 chris、terry 和 jack。
UPDATED:更新:
eg: chris.mydomain.com terry.mydomain.com jack.mydomain.com例如: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 chris.mydomain.com/d/3542re6s/somthing.html
would return会回来
3542re6s 3542re6s
Any help is very much appreciated.很感谢任何形式的帮助。
Thanks in advance C提前致谢
Your regular expression is missing the /d/
directory.您的正则表达式缺少/d/
目录。 Also, since the next level contains both numbers and letters, you can't use \\d+
to match it.此外,由于下一级同时包含数字和字母,您不能使用\\d+
来匹配它。 Try this:尝试这个:
$pattern = '#//(?:(?:chris|terry|jack)\.)?mydomain\.com/d/([^/]+)(?|/)#';
DEMO at regex101 regex101 上的演示
PHP demo at ideone ideone 上的 PHP 演示
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.我#
上面使用了#
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.