match any part of a URL
Can anyone help me figure out how to search a URL and print a class based on its result for example:
http://www.?.com/garden-design.html
开发者_开发知识库What i am trying to achieve is using a switch using PHP mathcing a term of say "garden" after the first trailing slash then it would print a class. If it matched construction it would print a different class. There are only three so i know which words to search for. This doesnt have to be dynamic.
Any help would be appreciated.
If it does not have to be dynamic, you could do it like this:
switch(true)
{
case stripos($_SERVER['REQUEST_URI'], 'garden'):
return 'garden';
break;
case stripos($_SERVER['REQUEST_URI'], 'construction'):
return 'construction';
break;
default:
return 'default';
break;
}
The above is quite explicit. A more compact solution could be
function getCategory($categories)
{
foreach($catgories as $category) {
if stripos($_SERVER['REQUEST_URI'], $category) {
return $category;
}
}
}
$categories = array('garden', 'construction', 'indoor');
echo getCategory($categories);
This will not give you the first word after /
, but just check if one of your keywords exists in the requested URI and return it.
You could also use parse_url to split the URI into it's components and work with String functions on the path
component, e.g.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
In www.example.com/garden-design.html?foo=bar
, this would give you just the part garden-design.html
. In your scenario you'd probably still do the stripos on it then, so you can just as well do it directly on the URL instead of parsing it.
I'd have thought that making use of parse_url
would probably be a good starting point - you could then explode
the path component and then do simply strpos
comparisons against the three strings you're looking for, if a simple switch statement isn't sufficient. (Be sure to check for !== false if you go down the strpos route.)
This would potentially be faster than a regex based solution.
You can try a regular expression:
/http://www..+.com/(garden|construction|indoor)(-design)?.html/
then $1 would give you garden, construction or indoor as string.
you can also use (.+)
to collect any string at that spot.
Update made "-design" optional.
Take a look at the php function strpos()
. With it you could do something like:
$url = "http://www.nothing.com/garden-design.html";
if (strpos($url, "/garden-design.html"))
doSomething();
else if (strpos($url, "/construction-design.html"))
doSomethingElse();
else if (strpos($url, "/indoor-design.html"))
doSomethingElseInstead();
String matching is generally quicker and more efficient than regular expressions.
精彩评论