带 preg_match 的 PHP 菜单
首先抱歉我的英语不好。
我在 PHP 中有这个菜单栏。我希望如果用户在页面上,当前菜单项会获得另一种颜色。我有一个有效的代码,但如果我有一个像 /item.php?id=9 这样的页面,它就不会工作。所以我用 preg_match 尝试了这个,但我无法让它工作。
菜单:
<li <?php unset($pageURL); getSelected("/index.php") ?>><a href="index.php">Home</a></li>
<li <?php unset($pageURL); getSelected("/item.php") ?>><a href="item.php">Item</a></li>
<li <?php unset($pageURL); getSelected("/more.php") ?>><a href="more.php">More</a></li>
函数 getSelected:
Function getSelected($nameURL){
$curURL =$_SERVER["REQUEST_URI"];
$pattern = "~$nameURL/.*~";
if(preg_match($pattern, $curURL)){
echo 'class="selected"';
unset($curURL);
}
unset($curURL);
}
如何使用 preg_match 修复此问题?
谢谢你!
First sorry for my bad English.
I have this menubar in PHP. I want that if an user is on a page the current menuitem gets another color. I had a code that works, but if i have a page like /item.php?id=9 , it wont work. So i tried this with preg_match, but i can't get it to work.
Menu :
<li <?php unset($pageURL); getSelected("/index.php") ?>><a href="index.php">Home</a></li>
<li <?php unset($pageURL); getSelected("/item.php") ?>><a href="item.php">Item</a></li>
<li <?php unset($pageURL); getSelected("/more.php") ?>><a href="more.php">More</a></li>
Function getSelected:
Function getSelected($nameURL){
$curURL =$_SERVER["REQUEST_URI"];
$pattern = "~$nameURL/.*~";
if(preg_match($pattern, $curURL)){
echo 'class="selected"';
unset($curURL);
}
unset($curURL);
}
How can i fix this with preg_match?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为
basename()
与parse_url()
会执行以下操作工作。它返回 URL 的文件名:在 HTML 中,例如:
这里不需要 RegEx。
I think
basename()
in combination withparse_url()
would do the job. It returns the filename of an URL:And in HTML e.g.:
No need for RegEx here.
在这种情况下,仅使用 php 字符串函数会更快(CPU 周期)且更容易(编码)。
It is faster (CPU cycles) and easier (coding) in this situation to just use a php string function.
它可能是
$pattern
中的尾随/
。尝试替换为
另外,我不确定,但你最好在
getSelected
调用中转义.
,因为使用你的模式/itemdphp
也会匹配。It might be the trailing
/
in$pattern
. Try replacingwith
Also, I'm not sure, but you'd better escape the
.
in yourgetSelected
calls, because with your pattern/itemdphp
will match too.您可以使用类似的内容
因为前面已经有一个
/
。You can use something like
Because you already have a
/
in the front .首先,没有理由多次取消设置变量。只需在开始时执行一次:
然后在函数中尝试以下正则表达式:
$pattern = "/\/$nameURL(.*)/";
getSelected('item.php' )
将匹配,例如/item.php
或/item.php?something=stuff&othervar=lollipop
First, there is no reason to unset a variable so many times. Just do it once at the beginning:
Then try the following regex in your function:
$pattern = "/\/$nameURL(.*)/";
getSelected('item.php')
will match, for example,/item.php
or/item.php?something=stuff&othervar=lollipop