danyo danyo - 29 days ago 7
PHP Question

php check if string contains a value in array

I am trying to detect whether a string contains at least 1 url that is stored in an array.

Here is my array:

$owned_urls= array('website1.com', 'website2.com', 'website3.com');


The string is user entered and submitted via php. On the confirmation page i would like to check if the url entered is in the array.

I have tried the following:

$string = 'my domain name is website3.com';
if (in_array($string,$owned_urls))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}


No matter what is inputted the return is always "Match not found".

Is this the correct way of doing things?

Answer

Try this.

$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
    //if (strstr($string, $url)) { // mine version
    if (strpos($string, $url) !== FALSE) { // Yoshi version
        echo "Match found"; 
        return true;
    }
}
echo "Not found!";
return false;

Use stristr() or stripos() if you want to check case-insensitive.