Home >Backend Development >PHP Tutorial >How to Match URLs with or Without Optional HTTP and WWW Prefixes Using a Regular Expression?

How to Match URLs with or Without Optional HTTP and WWW Prefixes Using a Regular Expression?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 08:42:03658browse

How to Match URLs with or Without Optional HTTP and WWW Prefixes Using a Regular Expression?

Matching URLs with Optional HTTP and WWW Prefixes

Regular expressions are powerful tools for complex pattern matching tasks. When it comes to matching URLs, there are often variations in the format, such as whether it includes "http://www." prefix or not.

Solution Using Regular Expression

To match URLs with or without the "http://www." prefix, the following regular expression can be used:

((https?|ftp)://)?
([a-z0-9+!*(),;?&=$_.-]+(:[a-z0-9+!*(),;?&=$_.-]+)?@)?
([a-z0-9\-\.]*)\.(([a-z]{2,4})|([0-9]{1,3}\.([0-9]{1,3})\.([0-9]{1,3})))
(:[0-9]{2,5})?
(/([a-z0-9+$_%-]\.?)+)*/?
(\?[a-z+&$_.-][a-z0-9;:@&%=+/$_.-]*)?
(#a-z_.-][a-z0-9+$%_.-]*)?

Breakdown of the Expression:

  • (https?|ftp):// - Optional protocol identifier (http or ftp)
  • ([a-z0-9 !*(),;?&=$_.-] (:[a-z0-9 !*(),;?&=$_.-] )?@)? - Optional user and password
  • ([a-z0-9-.]*).(([a-z]{2,4})|([0-9]{1,3}.([0-9]{1,3}).([0-9]{1,3}))) - Hostname or IP address
  • (:[0-9]{2,5})? - Optional port number
  • (/([a-z0-9 $_%-].?) )*/? - Optional path
  • (?a-z &$_.-*)? - Optional query string
  • (#a-z_.-][a-z0-9 $%_.-]*)? - Optional anchor

Example Usage

To check if a given string matches the regular expression, use the following syntax:

<code class="php">if(preg_match(~^$regex$~i, 'www.example.com/etcetc', $m))</code>

This will return TRUE if the string matches the URL pattern with or without the "http://www." prefix.

The above is the detailed content of How to Match URLs with or Without Optional HTTP and WWW Prefixes Using a Regular Expression?. 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