strip_tags加注释链接

时间:2010-09-23 09:11:16

标签: php html text

注意:输入HTML是可信的;它不是用户定义的!

我会用一个例子来强调我需要的东西。

给出以下HTML:

<p>
  Welcome to <a href="http://google.com/" class="crap">Google.com</a>!<br>
  Please, <a href="enjoy.html">enjoy</a> your stay!
</p>

我想将其转换为:

Welcome to Google.com[1]
Please, enjoy[2] your stay!

[1] http://google.com/
[2] %request-uri%/enjoy.html    <- note, request uri is something I define
                                   for relative paths

我希望能够自定义它。


编辑:进一步说明,我最好解释一下自己和我的理由

我们有一个用于电子邮件的自动模板系统(带有sylesheets!),作为系统的一部分,我想生成多部分电子邮件,即包含HTML和TEXT的电子邮件。 该系统仅提供HTML。

我需要将此HTML转换为有意义的文本,例如,我想以某种方式保留任何链接和图像,可能采用我上面指定的格式。

1 个答案:

答案 0 :(得分:0)

您可以使用DOM执行以下操作:

$doc = new DOMDocument();
$doc->loadHTML('…');

$anchors = array();
foreach ($doc->getElementsByTagName('a') as $anchor) {
    if ($anchor->hasAttribute('href')) {
        $href = $anchor->getAttribute('href');
        if (!isset($anchors[$href])) {
            $anchors[$href] = count($anchors) + 1;
        }
        $index = $anchors[$href];
        $anchor->parentNode->replaceChild($doc->createElement('a', $anchor->nodeValue." [$index]"), $anchor);
    }
}
$html = strip_tags($doc->saveHTML());
$html = preg_replace('/^[\t ]+|[\t ]+$/m', '', $html);
foreach ($anchors as $href => $index) {
    $html .= "\n[$index] $href";
}