簡體   English   中英

查找以“ X”開頭,以“ Y”結尾並在之間替換內容的字符串

[英]Find string that begins with “X” and ends with “Y” and replaces content between

我正在嘗試處理一些html並將所有img標簽src替換為base64。 我已經編寫了下面的函數來轉換圖像並在base64中返回它。 我需要以下幫助:

我需要使用str_replace,preg_replace或某種正則表達式來掃描某些html,並將所有“ src”替換為圖像的base64表示形式。 html存儲為變量而不是實際的html文檔。例如,如果我有一些類似html的代碼:

$htmlSample =  "<div>Some text, yada yada and now and image <img src='image1.png' /></div>"

我需要對其進行掃描並將src ='image.png'替換為base64等價物,例如src =“ data:image / png; base64,/ 9j / 4WvuRXhpZgAASUkqAAgAAAAIAA8BAgASAAAAbgAABAgAK” ---(這不是實際的base64,只是一些填充文本)。 該功能將需要能夠對html中的多個圖像執行此操作。 如果您能指出正確的方向,我將非常感激。 多謝你們!

function convertImage($file)
{


    if($fp = fopen($file,"rb", 0))
    {
       $picture = fread($fp,filesize($file));
       fclose($fp);
       $base64 = base64_encode($picture);
       $tag = '<img ' . "" .
          'src="data:image/png;base64,' . $base64 .
          '"  />';
       return $tag;
    }

}

查看DOM操作器,例如SimpleDOM。 這將使您以面向對象的方式解析html文檔,而不是凌亂的正則表達式,因為庫很可能會處理您可能不會想到的情況。

正如亞當建議的那樣,我能夠使用SimpleDOM(鏈接:simplehtmldom.sourceforge.net)完成此任務。

require_once('simple_html_dom.php');
$html = "This is some test code <img width='50' src='img/paddock1.jpg' /> And this is some additional text and an image: <img src='img/paddock2.jpg' />";

//uses function from simple_html_dom.php to make html parsable
$doc = str_get_html($html);

//finds each image in html and converts
foreach ($doc->find('img[src]') as $img) 
{

    //get src of image and assign to $src
    $src = $img->src;

    $imageBase = convertImage($src);

    $img->src = $imageBase;


}

$html = (string) $doc;

echo $html;

function convertImage($file)
{

    //finds file based on $src name from above and runs code if file exists
    if($fp = fopen($file,"rb", 0))
    {
       $picture = fread($fp,filesize($file));
       fclose($fp);
       //converts image file to base64
        $base64 = base64_encode($picture);

       //returns nessary data: + base64 code to $imageBase above to be inserted into html>img>src
       return 'data:image/png;base64,' . $base64;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM