Possible Duplicate:
PHP validation/regex for URL
Is there any easy, secure and fast way to check if a URL is valid in PHP?
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
Use the filter_var() function to validate whether a string is URL or not: var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
Yes, there is! Use filter_var
:
if (filter_var($url, FILTER_VALIDATE_URL) !== false) ...
FILTER_VALIDATE_URL
validates URLs according to RFC 2396.
Well if we look at RFC 3986 we can find the definition of a URL.
And if we take a look at Appendix B there is a guide to using regular expressions to parse a URL:
Appendix B. Parsing a URI Reference with a Regular Expression
As the "first-match-wins" algorithm is identical to the "greedy"
disambiguation method used by POSIX regular expressions, it is
natural and commonplace to use a regular expression for parsing the
potential five components of a URI reference.The following line is the regular expression for breaking-down a
well-formed URI reference into its components.^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? 12 3 4 5 6 7 8 9
The numbers in the second line above are only to assist readability; they indicate the reference points for each subexpression (i.e., each paired parenthesis). We refer to the value matched for subexpression as $. For example, matching the above expression to
http://www.ics.uci.edu/pub/ietf/uri/#Related
results in the following subexpression matches:
$1 = http: $2 = http $3 = //www.ics.uci.edu $4 = www.ics.uci.edu $5 = /pub/ietf/uri/ $6 = <undefined> $7 = <undefined> $8 = #Related $9 = Related
where indicates that the component is not present, as is the case for the query component in the above example. Therefore, we can determine the value of the five components as
scheme = $2 authority = $4 path = $5 query = $7 fragment = $9
Going in the opposite direction, we can recreate a URI reference from its components by using the algorithm of Section 5.3.
You can ues this regular expression to parse the URL manually or use the built in parse_url function avalable in PHP 4 and 5
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