How to check if URL contains certain words?

1.7k Views Asked by At

I want to show custom content if current URL contain certain words.

So far, I'm able to achieve this if the URL contains just the word, 'cart', using the code below. However, I want to be able to check for other words like 'blog', 'event' and 'news'. How do I go about this.

<?php $path = $_SERVER['REQUEST_URI'];
$find = 'cart';
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) : 
            ?>
  Custom content      
<?php else: ?>
3

There are 3 best solutions below

1
On

Use an Array and loop through it .. IE

<?php $path = $_SERVER['REQUEST_URI'];
$arr = array();
$arr[0] = 'cart';
$arr[1] = 'foo';
$arr[2] = 'bar';

foreach($arr as $find){

   $pos = strpos($path, $find);
   if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false){ 
      echo "custom content";
      break; // To exit the loop if custom content is found -- Prevents it showing twice or more
    }      
}
0
On

There are several solutions such as preg_match_all():

Code

<?php $path = $_SERVER['REQUEST_URI'];
$find = '/(curt|blog|event|news)/i';
$number_of_words_in_my_path  = preg_match_all($find, $path);
if ($number_of_words_in_my_path > 0 && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) : 
            ?>
  Custom content
<?php else: ?>
0
On

Use an array but use preg_grep instead. IMO it's the correct preg_ function for this use case.

preg_grep — Return array entries that match the pattern

 //www.example.com?foo[]=somewords&foo[]=shopping+cart

//for testing
$_GET['foo'] = ['somewords', 'shopping cart'];

$foo = empty($_GET['foo']) ? [] : $_GET['foo'];

$words = ['cart','foo','bar'];

$words = array_map(function($item){
             return preg_quote($item,'/');
        },$words);

$array = preg_grep('/\b('.implode('|', $words).')\b/', $foo);

print_r($array);

Output

Array
(
    [1] => shopping cart
)

Sandbox