Home  >  Article  >  Backend Development  >  How to Detect URLs in User Input and Compare Them Against a Predefined Array in PHP?

How to Detect URLs in User Input and Compare Them Against a Predefined Array in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 05:25:02562browse

How to Detect URLs in User Input and Compare Them Against a Predefined Array in PHP?

Detecting URLs in User Input

In PHP, determining whether a user-entered string contains a URL from a predefined array can be achieved through various methods.

One approach is to utilize PHP's in_array() function. However, in the provided code, the comparison fails due to a mismatch between the string and array elements. The string contains a URL as part of a larger sentence, whereas the array elements are just base URLs.

An alternative method involves iterating through the array of URLs and checking if each one is present within the string using PHP's strpos() function. If any URL is found within the string, the function returns a non-FALSE value, indicating a match.

Here's the modified code:

<code class="php">$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
    if (strpos($string, $url) !== FALSE) {
        echo "Match found"; 
        return true;
    }
}
echo "Not found!";
return false;</code>

Alternatively, PHP's strstr() function can be used for case-insensitive comparisons. However, strpos() is generally preferred for its better performance.

To ensure the comparison is case-insensitive, the script can be modified as follows:

<code class="php">if ( stripos($string, $url) !== FALSE ) {
    // ...
}</code>

The above is the detailed content of How to Detect URLs in User Input and Compare Them Against a Predefined Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn