I want to convert a URL to regular expression to match it with current URL. For example, I have a URL http://www.example.com/example.php I want it to convert to ^(https?://)?(www\\.)?example\\.com\\/example\\.php/?(\\?. )?(#. )?$
So that I store it and whenever a user hits this url with any number of parameters attached to it, I will match that url with my regular expression and will perform some action based on the results.
I have found many questions but they all are either to match general URL (with any domain name) or with regular expressions given. But I want a function to which I will pass URL and it will return its regular expression and I will use it to match that specific domain.
I have finally created this code with the help of stackoverflow and other communities. This provides me the exact string I require against given URL.
<?php
function createrRegex($url) {
$var1 = '^(https?://)?';
$host = parse_url($url, PHP_URL_HOST);
$host_parts = explode('.', $host);
if (!empty($host_parts)) {
$length = count($host_parts);
foreach ($host_parts as $i => $part) {
if ($i == 0) {
if ($part == "www") {
$var1 .= '(' . $part . '\\\\.)?';
} else {
$var1 .= '' . $part;
$var1 .= ($i < ($length - 1)) ? '\\\\.' : '';
}
} else {
$var1 .= '' . $part;
$var1 .= ($i < ($length - 1)) ? '\\\\.' : '';
}
}
}
$path = '';
if ((parse_url($url, PHP_URL_PATH) != NULL)) {
$path = str_replace('/', '\\\\/', parse_url($url, PHP_URL_PATH));
$path = str_replace('.', '\\\\.', $path);
}
$var1 .= $path;
$var1 .= '/?(\\\\?.*)?(#.*)?$';
return $var1;
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.