Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains a value in array [duplicate]

Tags:

arrays

php

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

Here is my array:

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

The string is entered by the user 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?

like image 269
danyo Avatar asked Oct 18 '13 09:10

danyo


People also ask

How do you check if a string is repeated in an array?

Check if a String is contained in an Array using indexOf # We used the Array. indexOf method to check if the string two is contained in the array. If the string is not contained in the array, the indexOf method returns -1 , otherwise it returns the index of the first occurrence of the string in the array.

Can array have duplicate values?

The standard way to find duplicate elements from an array is by using the HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements.

How do you check if there are duplicates in an array C++?

Using Set A simple and elegant solution is to construct a set from the array which retains only distinct elements. Then simply compare the set's size against the array's length. If both are not the same, then we can say that the array contains duplicates. This works in linear time and space.


2 Answers

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.

like image 59
Daniele Vrut Avatar answered Oct 13 '22 07:10

Daniele Vrut


Try this:

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

- Thanks

like image 30
Anand Solanki Avatar answered Oct 13 '22 06:10

Anand Solanki