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

Barbara Streisand
Release: 2024-10-25 05:25:02
Original
561 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!