PHP Menu with 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!
I think basename()
in combination with parse_url()
would do the job. It returns the filename of an URL:
function getSelected($nameURL){
$currentfile = basename(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH));
if($currentfile === $nameURL){
echo 'class="selected"';
}
}
And in HTML e.g.:
<li <?php getSelected("item.php") ?>><a href="item.php">Item</a></li>
No need for RegEx here.
It is faster (CPU cycles) and easier (coding) in this situation to just use a php string function.
if (stripos($curURL, $pattern) !== false) {
echo 'class="selected"'
}
It might be the trailing /
in $pattern
. Try replacing
$pattern = "~$nameURL/.*~";
with
$pattern = "~$nameURL/?.*~";
Also, I'm not sure, but you'd better escape the .
in your getSelected
calls, because with your pattern /itemdphp
will match too.
You can use something like
$pattern = $nameURL . '$/';
preg_match($pattern, $_SERVER['SCRIPT_FILENAME']);
Because you already have a /
in the front .
First, there is no reason to unset a variable so many times. Just do it once at the beginning:
<?php unset($pageURL);?>
<li <?php getSelected("/index.php") ?>><a href="index.php">Home</a></li>
<li <?php getSelected("/item.php") ?>><a href="item.php">Item</a></li>
<li <?php getSelected("/more.php") ?>><a href="more.php">More</a></li>
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
精彩评论