[英]php preg_match '/' with regex
I'm matching routes, so If I have a string 我正在匹配路线,所以如果我有一个字符串
"/teacher/jkDfl"
and I want to check if it starts with 我想检查一下是否以
"/teacher/"
My newbie approach is hoping this evaluates to true 我的新手方法希望这能评估为真
preg_match("/^/teacher//", "/teacher/jkDfl")
But I think the issue is all the '/'
characters, and looking around nothing popped out at me. 但是我认为问题出在所有
'/'
字符上,到处都看不到我。 I probably need to work on my google-fu, but I figure this is simple for someone with xp in regex. 我可能需要在Google-fu上工作,但是我认为对于正则表达式中具有xp的人来说,这很简单。
Cheers! 干杯!
Delimiters are somewhat arbitrary, so, the often used #
delimiter would work: 分隔符在某种程度上是任意的,因此,常用的
#
分隔符将起作用:
preg_match("#^/teacher/#",....
If you're very fond of /
's, you can escape them with \\
's: 如果您非常喜欢
/
,则可以使用\\
进行转义:
preg_match("/^\/teacher\//",....
... or let PHP do that for you (good for user provided literal strings): ...或让PHP为您做到这一点(适用于用户提供的文字字符串):
preg_match("/^".preg_quote("/teacher/","/")."/",...
You can use # as regexp delimiter. 您可以使用#作为正则表达式分隔符。
preg_match("#^/teacher/#", "/teacher/jkDfl")
You could also capture the various parameters (eg jkDfl) with regexps, see: 您还可以使用正则表达式捕获各种参数(例如jkDfl),请参见:
http://php.net/manual/en/function.preg-match.php http://php.net/manual/zh/function.preg-match.php
In this case: 在这种情况下:
if (preg_match("#^/teacher/([^?]*)#", $url, $gregs))
{
$teacher = $gregs[1]; // "jkDfl"
....
}
You have two options: change the delimiter or escape the literals. 您有两种选择:更改定界符或对文字进行转义。
Different delimiter: 不同的定界符:
preg_match("%^/teacher/%", "/teacher/jkDfl");
Escape literals: 转义文字:
preg_match("/^\/teacher\//", "/teacher/jkDfl");
//or
preg_match("/^" . preg_quote("/teacher/", "/") . "/", "/teacher/jkDfl");
它应该是
preg_match("/^\/teacher\//", "/teacher/jkDfl")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.