a.m
a.m

Reputation: 169

Check for certain word in the URL with PHP

I am trying to write a php code, that checks if there is a certain word in the url and if so - show something.

I am using this one:

$url = parse_url($_SERVER['REQUEST_URI']);

if($url['path'] == '/main-category/') {
echo........

For example I am looking for "main-category". For http://www.site.com/main-category/ the code is working, but if the url contains subcategory http://www.site.com/main-category/sub-category/, it isn't.

How can I make it find /main-category/ no matter if there is something after it, or not?

I read some topics here but didn't figure it out.

Upvotes: 1

Views: 3175

Answers (1)

John Conde
John Conde

Reputation: 219804

Use strpos(). Example from the manual:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Upvotes: 7

Related Questions