Search code examples
phpurlrelative-pathabsolute-path

PHP: replace relative urls to absolute urls in a textarea


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);
  1. The problem is that it needs a / in the start of the value and therefore a URL like href=somefolder/somefile would not be replaced.
  2. I also would like it to work if there are spaces before or / 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).


Solution

  • 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.