2013-03-14 106 views
0

之间的内容我试图处理一些html并用base64替换所有img标签src。我已经编写了下面的函数来转换图像并以base64形式返回。我需要帮助的是以下内容:查找以“X”开头并以“Y”结尾的字符串并替换

我需要使用str_replace,preg_replace或某种正则表达式来扫描一些html,并用图像的base64表示替换所有“src”。的HTML被存储为变量,而不是作为一个实际的HTML document.For例如,如果我有一些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; 
    } 

} 
+2

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#answer-1732454正则表达式是不正确的工具。刚说。 – KingCrunch 2013-03-14 00:03:03

+1

[getElementsByTagName()](http://www.php.net/manual/en/domdocument.getelementsbytagname.php),[getAttribute()](http://www.php.net/manual/en/domelement。 getattribute.php),[setAttribute()](http://www.php.net/manual/en/domelement.setattribute.php)。 – Wrikken 2013-03-14 00:06:44

+0

[How to parse and process HTML/XML with PHP?](http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-xml-with-php) – Wrikken 2013-03-14 00:08:03

回答

0

正如亚当所说,我能够使用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; 
    } 
} 
1

查看一个DOM操纵器,如SimpleDOM。这会让你以更加面向对象的方式解析html文档,而不是混乱的正则表达式,因为这些库更有可能处理你可能不会想到的情况。

+0

html被存储为变量而不是实际的html文档。 SimpleDOM仍然可以用于这样的事情吗? – ajodom10 2013-03-14 00:28:57

+0

是SimpleDOM有多种方法通过变量,URL或文件加载页面。我刚刚找到链接:http://simplehtmldom.sourceforge.net。文档也很简单。 – Adam 2013-03-14 01:14:46

相关问题