0

I am trying to check a URL, to see if it has any matching terms from my array.

My code is:

function test_string_in_url () {

$the_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

$my_array = array(
    'word1',
    'word2',
    'word3',
);

if (strpos( $the_url, $my_array ) !== false)
    // do something

    else {
    // do nothing
    }
}

This always returns false though, which is incorrect. It should only return true because I do have matching terms in my URL, so I must be doing something wrong here...

Brett
  • 359
  • 3
  • 16
  • Possible duplicate of [Using an array as needles in strpos](https://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos) –  Feb 27 '18 at 03:54
  • @rtfm - I tried the solution in there, but it does not work in my case sorry – Brett Feb 27 '18 at 03:59
  • please try my below code and let me know its working for you – developerme Feb 27 '18 at 04:01
  • post what you actually tried, because there's no reason that the answer from the other post should not have worked –  Feb 27 '18 at 04:05

2 Answers2

1

You can try this code

$my_array = array('test1', 'test2', 'test3');
$the_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
foreach ($my_array as $url) {

    if (strpos($the_url, $url) !== FALSE) { 
        echo "Match found"; 
        return true;
    }
}
echo "Not found!";
return false;
developerme
  • 1,845
  • 2
  • 15
  • 34
1

It is returning false because you are passing array as needle to strpos which accepts only integer or string as parameter thats why it was returning false always.Check the solution this resolves it.

<?php

function test_string_in_url () {

 $the_url = 'http://' . $_SERVER['SERVER_NAME'] .     $_SERVER['REQUEST_URI'];

 $my_array = array(
'word1',
'word2',
'word3');
foreach($my_array as $val)
{
    if (strpos( $the_url, $val) !== false)
    {
       //do something
        break;
    }
else {
        // do nothing
}
}//foreach
}//function
test_string_in_url ();
?>
Hp_issei
  • 579
  • 6
  • 18