I just wanted to share this with you guys, because otherwise I might forget it: This is a simple method to prefix the src -attribute of an img -tag with a specific domain name. This method takes HTML like:
1 2 3 4 5 6 |
<p>Hello</p><img src="/path/to/image.jpg" /><p>World</p> <p>Hello</p><img src="path/to/image.jpg" /><p>World</p> <p>Hello</p><img src="/path/to/image.jpg" /><p>World</p><p><img src="yolo.jpg" /></p> <p>Hello</p><img alt="foo" src="/path/to/image.jpg" title="bar" /><p>World</p> <p>Hello</p><img title="foo" src="http://www.example.com/path/to/image.jpg" /><p>World</p><p><img alt="bar" src="/yolo.jpg" /></p> <p>Hello</p><img title="foo" src="http://www.foo.com/path/to/image.jpg" /><p>World</p><p><img alt="bar" src="http://www.bar.com/yolo.jpg" /></p> |
And prefixes it like this:
1 2 3 4 5 6 |
<p>Hello</p><img src="http://www.example.com/path/to/image.jpg" /><p>World</p> <p>Hello</p><img src="http://www.example.com/path/to/image.jpg" /><p>World</p> <p>Hello</p><img src="http://www.example.com/path/to/image.jpg" /><p>World</p><p><img src="http://www.example.com/yolo.jpg" /></p> <p>Hello</p><img alt="foo" src="http://www.example.com/path/to/image.jpg" title="bar" /><p>World</p> <p>Hello</p><img title="foo" src="http://www.example.com/path/to/image.jpg" /><p>World</p><p><img alt="bar" src="http://www.example.com/yolo.jpg" /></p> <p>Hello</p><img title="foo" src="http://www.foo.com/path/to/image.jpg" /><p>World</p><p><img alt="bar" src="http://www.bar.com/yolo.jpg" /></p> |
This is ideal for when you got HTML from WYSIWYG-editors for example that don’t always prefix the image tag, or other sources that don’t add a domain name to the image tag. So here’s the method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/** * Add absolute URL to <img>-tag * @param string $html The HTML to check * @param string $path The path to prefix * @return string */ public function prefixImgSrc($html, $path) { $regExp = '/<img.*src=["\'](.*)["\'].*\/>/mUis'; $path = trim($path, '/'); preg_match_all($regExp, $html, $matches); if(count($matches[0]) > 0) { foreach($matches[0] as $idx => $match) { if(strpos($matches[1][$idx], 'http') === false) { $newUrl = str_replace($matches[1][$idx], $path . '/' . trim($matches[1][$idx], '/'), $match); $html = str_replace($match, $newUrl, $html); } } } return $html; } |
Visitors give this article an average rating of 3.0 out of 5.
How would you rate this article?
★ ★ ★ ★ ★