John Davidson

php - Add domain to <img> src attribute value if a relative path

0 comments
Message:


I have a text variable which contains multiple images with a relative or absolute path. I need to check if the src attribute starts with http or https then ignore it, but in case it starts with / or something like abc/ then prepend a base url.


I tried like below:


<?php
$html = <<<HTML
<img src="docs/relative/url/img.jpg" />
<img src="/docs/relative/url/img.jpg" />
<img src="https://docs/relative/url/img.jpg" />
<img src="http://docs/relative/url/img.jpg" />
HTML;

$base = 'https://example.com/';

$pattern = "/<img src=\"[^http|https]([^\"]*)\"/";
$replace = "<img src=\"" . $base . "\${1}\"";
echo $text = preg_replace($pattern, $replace, $html);

My output is:


<img src="https://example.com/ocs/relative/url/img.jpg" />
<img src="https://example.com/docs/relative/url/img.jpg" />
<img src="https://docs/relative/url/img.jpg" />
<img src="http://docs/relative/url/img.jpg" />

Issue here: I got 99% result correct, but when the src attribute started with something like docs/ then first letter of it cut off. (please check first img src in output)


Output I needed is:


<img src="https://example.com/docs/relative/url/img.jpg" /><!--check this and compare with current result, you will get the difference -->
<img src="https://example.com/docs/relative/url/img.jpg" />
<img src="https://docs/relative/url/img.jpg" />
<img src="http://docs/relative/url/img.jpg" />

Could any one help me to rectify it.



My Answer:
a URL in PHP can be done using the following code:

php
$url = "example.com/page";
$domain = "https://www.";
$newUrl = $domain . $url;

echo $newUrl;


This code will output: `https://www.example.com/page`

Rate this post

5 of 5 based on 3154 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us