从字符串中获取图像上传它们并替换为新链接

时间:2015-10-10 21:36:14

标签: php regex dom preg-replace

我有一个包含文字和照片的字符串,如下所示。 到目前为止我的代码获取所有图像并将其上传到文件夹中。 我需要用正确的矿工替换新上传的链接。

$nextstep = "Hello there this is image 1 <img src='http://www.demosite.com/wp-content/uploads/2015/01.jpg' width='653' height='340' alt='xxx' title='xxx'> !! And Now you can see image number 2 <img src='http://www.demosite.com/wp-content/uploads/2015/02.jpg' width='653' height='340' alt='xxx' title='xxx'>";

$string = $nextstep;
$doc = new DOMDocument();
$doc->loadHTML($string);
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) { //STARTING LOOP
    echo "</br>";
    echo $image->getAttribute('src') . "\n";
    echo "</br>";
    $urlimg = $image->getAttribute('src'); //IMAGE URL
    $URL = urldecode($urlimg);
    $image_name = (stristr($URL,'?',true))?stristr($URL,'?',true):$URL;
    $pos = strrpos($image_name,'/');
    $image_name = substr($image_name,$pos+1);
    $extension = stristr($image_name,'.');
    if($extension == '.jpg' || $extension == '.png' || $extension == '.gif' || $extension == '.jpeg'){
        $img = '../images/' . $image_name;
        file_put_contents($img, file_get_contents($url)); //UPLOAD THEM ONE BY ONE
    }
}

1 个答案:

答案 0 :(得分:1)

目前还不清楚预期的结果是什么。您似乎想要将现有字符串中的src网址更改为您已保存图片的网址。如果情况并非如此,请尝试更新问题以获得更清晰的信息。

这是解决问题的简单方法......

步骤1 - 使用源字符串

从DOM中提取img标记
$html = <<<'HTML'
Hello there this is image 1 <img src="http://www.demosite.com/wp-content/uploads/2015/01.jpg" width="653" height="340" alt="xxx" title="xxx"> !! 

And Now you can see image number 2 <img src="http://www.demosite.com/wp-content/uploads/2015/02.jpg" width="653" height="340" alt="xxx" title="xxx">
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');

// Store the list of image urls in an array - this will come in handy later
$imgURLs = [];
foreach($imgs as $img) {
    if (!$img->hasAttribute('src')) {
        continue;
    }
    $imgURLs[] = $img->getAttribute('src');
}

步骤2 - 将图像保存在其他位置

$newImgURLs = [];          // new modified URLs where images were moved
$newPath    = '../images'; // wherever you're saving the images
foreach($imgURLs as $imgURL) {
    /**
     *  Use parse_url and pathinfo to break down the URL parts and extract the
     *  filename/extension instead of the fragile implementation you used above
     */
    $URLparts     = parse_url($imgURL);
    $file         = pathinfo($URLparts['path']);
    $fileName     = $file['filename'] . '.' . $file['extension'];
    $newFileName  = $newPath . '/' . $fileName;
    $newImgURLs[] = $URLparts['scheme'] . '://' .
                    $URLparts['host'] . $file['dirname'] . '/' . $newFileName .
                    (isset($URLparts['query']) ? ('?' . $URLparts['query']) : null) .
                    (isset($URLparts['fragment']) ? ('#' . $URLparts['fragment']) : null);
    // download image and save to new location
    file_put_contents($newFileName, file_get_contents($imgURL));
}

步骤3 - 将img src URL修改为新路径

foreach($imgs as $i => $img) {
    $img->setAttribute('src', $newImgURLs[$i])
}
echo $dom->saveHTML(); // new updated DOM
// or just create a new $html string from scratch using the new URLs.