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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With