之间的内容我试图处理一些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;
}
}
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#answer-1732454正则表达式是不正确的工具。刚说。 – KingCrunch 2013-03-14 00:03:03
[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
[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