Reputation:
I'm trying to validate a URL using a Regex with PHP. I need a pattern that considers valid:
Any other is not valid, so you can't have ssh://, a .com domain, etc.
I tried the following pattern:
/(((http|ftp|https):\/{2})+(([0-9a-z_-]+\.)+(pf)(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%@\.\/_-]+))?(\?[0-9a-zA-Z\+\%@\/&\[\];=_-]+)?)?))\b/imuS
but I've lost many hours (and hairs) trying to make it work the way I need it to work.
Any suggestion is appreciated.
Upvotes: 2
Views: 324
Reputation: 570
^((http|ftp)[s]?://)?([\w-/.]+)(.pf)([\w-/.\&\%\$+\?]+)?$
Handles everything requested, unless I interpret the question wrong. Test here: http://www.cuneytyilmaz.com/prog/jrx/ Please, do tick case insensitive.
to implement in php use /^((http|ftp)[s]?://)?([\w-/.]+)(.pf)([\w-/.\&\%\$+\?]+)?$/i
Upvotes: 0
Reputation: 3854
This is a better way of doing what you want, granted it doesn't use regular expressions, but it is easier to maintain and uses native php functions for that reason:
<?php
function isValidPFurl($url) {
if (strpos($url, "://" ) === false) {
$url = 'http://' . $url;
}
$valid = filter_var($url, FILTER_VALIDATE_URL);
if ($valid !== false) {
$parsed = parse_url($valid);
$host = $parsed['host'];
$scheme = $parsed['scheme'];
$valid = false;
switch($scheme) {
case 'ftp':
case 'http':
case 'https':
$p = explode(".", $host);
if ($p[sizeof($p) - 1] == 'pf') {
$valid = true;
}
break;
default:
$valid = false;
}
}
return $valid;
}
$testUrls = array(
"http://example.pf/",
"example.pf",
"www.example.pf",
"ftp://example.pf",
"https://example.pf",
"ssl://example.pf"
);
foreach ($testUrls as $url) {
echo "is $url valid? ", (int) isValidPFurl($url), "\n";
}
Upvotes: 0
Reputation: 392
Try this
/((https?|ftp):\/\/.)?(www\.)?[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*\.pf/i
I am not sure whether this is the best solution.
Upvotes: 1
Reputation: 10131
As per your need, you have to try this
<?php
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
?>
Upvotes: -1