查找图像源并为图像标记添加前缀



我有一个用于博客的字符串,可能这个字符串中可能有无限数量的图像,我试图做的是获取所有src=""并向url添加一个prefix并将其用作超链接。

我的字符串:

$test = 'Hello world
<img src="images/image1.jpg" />Line 2
<img src="images/image2.jpg" />Some text 
<img src="images/image3.jpg" />';

我可以在href前面添加前缀。我能够实现这一点:

<a href="images/image1.jpg"><img src="images/image1.jpg" /></a>
<a href="images/image1.jpg"><img src="images/image2.jpg" /></a>
<a href="images/image1.jpg"><img src="images/image3.jpg" /></a>

这是我到目前为止的代码:

$new = preg_replace('/(<img[^>]+src="([^\"]+)"[^>]+\/>)/','<a href="\2">\1</a>',$test2);
echo $new;

我需要在所有图像src中添加foldername/作为前缀。我试图将其变成以下内容:

<a href="images/image1.jpg"><img src="foldername/images/image1.jpg" /></a>
<a href="images/image1.jpg"><img src="foldername/images/image2.jpg" /></a>
<a href="images/image1.jpg"><img src="foldername/images/image3.jpg" /></a>

我该怎么做?

要使用 DOMDocument 而不是正则表达式来做到这一点(一个很好的理由是 https://stackoverflow.com/a/1732454/1213708(。

代码加载 HTML,然后查找所有<img>标记。 它首先取src的值,并向其添加额外的部分。 然后,它会创建一个新的<a>标记,并将(原始(src值添加为href属性。 然后,它将<img>标签替换为<a>,但将旧值添加回<a>...

$dom = new DOMDocument();
$dom->loadHTML($test, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ( $dom->getElementsByTagName("img") as $image ) {
$src = $image->getAttribute("src");
$image->setAttribute("src", "foldername/".$src);
$anchor = $dom->createElement("a");
$anchor->setAttribute("href", $src);
$image->parentNode->replaceChild($anchor, $image);
$anchor->appendChild($image);
}
echo $dom->saveHTML();

现在并不重要,但这是一个没有正则表达式的解析解决方案。实际上@NigelRen我更喜欢它发布的解决方案。但是,这里有一种方法可以构建没有正则表达式的图像 url 列表,可用于解决您的问题并提供进一步的探索。我还没有测试过代码,但我对它的工作很公平。

<?php
$html = 'some html here';
$sentinel = '<img src="';
$quoteSentinel = '"';
$done = false;
$offset = 0;
$imageURLS = array();
while (!$done) {
$nextImageTagPos = strpos($html, $sentinel, $offset);
if ($nextImageTagPos !== false) {
//*** Parsing
// Find first quote
$quoteBegins = false;
for ($i = $nextImageTagPos; $i < $nextImageTagPos + 100; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteBegins = $i;
break;
}
}
// Find ending quote
$quoteEnds = false;
if ($quoteBegins !== false) {
for ($i = $quoteBegins + 1; $i < $quoteBegins + 1000; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteEnds = $i;
break;
}
}
if ($quoteEnds !== false) {
// Hooray! now we are getting somewhere
$imgUrlLength = ($quoteEnds - $quoteBegins) - 1;
$imgUrl = substr($html, $quoteBegins + 1, $imgUrlLength);
// ***Requirements
/*
I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what i am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
*/
// But for brevity lets skip requirements and build an array of URLs.
$imageURLS[] = $imgUrl;
$offset = $quoteEnds + 1;


}
}
// Extract url
}
else {
$done = true;
}

}   

最新更新