I would like to replace relative URLs to absolute URLs in a textarea. So something like this:
/somefolder/somefile
Is replaced to:
http://www.mysite123.com/somefolder/somefile
I have this replace function to do the job:
$replaceStrs = array('href=/', "href='/", 'href="/');
$datdescription = str_ireplace($replaceStrs, 'href="http://www.' . $domain . "/", $datdescription);
/
in the start of the value and therefore a URL like href=somefolder/somefile
would not be replaced. /
and after the =
in the href
part. Point 1 is most important. Can you help to improve this?
I have seen PHP examples that replaces relative URLs to absolute URLs like this one .
But the requirement is that the relative URL is known /
found but in my case I have not managed this part (I am working with replacing all URLs in a textarea).
PHP:
function expand_links($link) {
return('href="http://example.com/'.trim($link, '\'"/\\').'"');
}
$textarea = preg_replace('/href\s*=\s*(?<href>"[^\\"]*"|\'[^\\\']*\')/e', 'expand_links("$1")', $textarea);
I also changed the regex to work with either double quotes or apostrophes.
Why all this fuss when a PHP function can already do this for you?
http://php.net/manual/en/function.http-build-url.php
PS: It seems it's only available on PECL. I just tested my Hostgator VPS (standard CentOS 5 repos) as well as my test WAMP environment, and it seems to be available on both.
NB: Also, you REALLY shouldn't blindly replace HTML fragments. First of all, it may not work eventually (encoding issues), secondly, it may add security issues to your code.
I expanded Mihai Stancu answer for you!
<?php
function expand_hrefs($link, $url) {
return('href="http://'.$url.'/'.trim($link, '\'"/\\').'"');
}
function expand_srcs($link, $url) {
return('src="http://'.$url.'/'.trim($link, '\'"/\\').'"');
}
$html = preg_replace('/href\s*=\s*(?<href>"[^\\"]*"|\'[^\\\']*\')/e', 'expand_hrefs("$1", "'.$url.'")', $html);
$html = preg_replace('/src\s*=\s*(?<src>"[^\\"]*"|\'[^\\\']*\')/e', 'expand_srcs("$1", "'.$url.'")', $html);
?>
This is MY first answer..
Stackoverflow.com is Brilliant!
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.