Php 在HTML电子邮件中嵌入图像–;取代;src";属性<;img>;

Php 在HTML电子邮件中嵌入图像–;取代;src";属性<;img>;,php,preg-replace,swiftmailer,Php,Preg Replace,Swiftmailer,可能重复: 我有一个cms,客户可以自己制作HTML时事通讯。通过Swift邮件发送给选定的接收者。这些时事通讯中包含链接到在线来源的图像。我想将这些图像嵌入电子邮件本身,这是Swift mailer支持的功能 我想做到的是,客户可以创建自己的新闻稿,包括链接到图像。发送此链接图像时,必须将其替换为将其嵌入电子邮件所需的代码。因此,我需要替换图像的来源: <img src="http://source/to/file.gif" /> 致: embed(Swift\u Imag

可能重复:

我有一个cms,客户可以自己制作HTML时事通讯。通过Swift邮件发送给选定的接收者。这些时事通讯中包含链接到在线来源的图像。我想将这些图像嵌入电子邮件本身,这是Swift mailer支持的功能

我想做到的是,客户可以创建自己的新闻稿,包括链接到图像。发送此链接图像时,必须将其替换为将其嵌入电子邮件所需的代码。因此,我需要替换图像的来源:

<img src="http://source/to/file.gif" />

致:

embed(Swift\u Image::fromPath('http://http://source/to/file.gif'))}" />
HTML内容(包括链接图像)存储在变量$content中。我试图用以下内容替换src:

$content = preg_replace(
    '/<img.*src="(.*?)".*?>/',
    '<img src="' . $message->embed(Swift_Image::fromPath('\1"')) . '" />',
    $content);
$content=preg\u replace(
'//',
'embed(Swift_Image::fromPath('\1'')。'“/>',
$content);

我遵循了DOM解析器的建议,它很有效。我正在使用

替换所有img src:

require_once("../../simple_html_dom.php");
$content = str_get_html($content);

// Retrieve all img src tags and replace them
foreach($content->find('img') as $e) 
    {
        if($e->src != "") 
            {
                $value = $e->src;
                echo $value;
                $newValue = $message->embed(Swift_Image::fromPath($value)); 
                $e->src = $newValue;
            }
    }
// Retrieve all background tags and replace them
foreach($content->find('td') as $e) 
    {
        if($e->background != "") 
            {
                $value = $e->background;
                $newValue = $message->embed(Swift_Image::fromPath($value)); 
                $e->background = $newValue;
            }
    }
替换背景标签的内容:

require_once("../../simple_html_dom.php");
$content = str_get_html($content);

// Retrieve all img src tags and replace them
foreach($content->find('img') as $e) 
    {
        if($e->src != "") 
            {
                $value = $e->src;
                echo $value;
                $newValue = $message->embed(Swift_Image::fromPath($value)); 
                $e->src = $newValue;
            }
    }
// Retrieve all background tags and replace them
foreach($content->find('td') as $e) 
    {
        if($e->background != "") 
            {
                $value = $e->background;
                $newValue = $message->embed(Swift_Image::fromPath($value)); 
                $e->background = $newValue;
            }
    }

如果您真的想使用正则表达式,请更正它。->使用ungreedy(u)marker避免正则表达式转到文档的最后一个
“*?>”
模式->使用$1表示“捕获的第一个模式”->字符串必须是:
'embed(Swift\u Image::fromPath('\1')。““/>”
您将以“然后在$message->之前关闭”开头替换字符串,并使用,与字符串结尾相同。我使用DOM解析器添加了我的解决方案。谢谢大家和我一起思考。@Klaaz提供您自己的解决方案的正确方法是提供答案,而不是对您的问题进行编辑。由于这是一个重复的问题,您可能希望删除您的问题,因为提供您的解决方案作为答案不会为未来的访问者增加任何价值。我知道,但我没有足够的分数在8小时内添加我自己的答案,因为我的状态不允许我添加答案。当我能够提供我自己的答案时(大约6小时内),我会纠正这个问题。注意:'Simple DOM Parser'不能很好地转换回纯文本,特别是标记。我遇到了一个问题,就是它没有添加新行,目前我正在使用“html2text”,它可以很好地将其格式化为纯文本,可通过