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...

4
  • Possible duplicate of Using an array as needles in strpos Commented Feb 27, 2018 at 3:54
  • @rtfm - I tried the solution in there, but it does not work in my case sorry Commented Feb 27, 2018 at 3:59
  • please try my below code and let me know its working for you Commented Feb 27, 2018 at 4:01
  • post what you actually tried, because there's no reason that the answer from the other post should not have worked Commented Feb 27, 2018 at 4:05

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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 ();
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.