2010-09-23 62 views
0

注意:输入HTML是可信的;它不是用户定义的!strip_tags plus注释链接

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

给出下面的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有意义地转换为文本,例如,我想以某种方式保留任何链接和图像,可能采用上面指定的格式。

+0

样式表中的电子邮件不是朋友。 – fabrik 2010-09-23 09:37:42

+0

fabrik - 这就是为什么我的系统像一个魅力工作;)。它不仅仅是将样式表放入文档中... – Christian 2010-09-23 10:20:02

回答

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"; 
}