如何在PHP中使用SimpleDomainParser将整个HTML标记替换为它们的alt文本等价物?
下面是一个例子: 我有一个DOM对象,如何在PHP中使用SimpleDomainParser将整个HTML标记替换为它们的alt文本等价物?,php,replace,simple-html-dom,html,Php,Replace,Simple Html Dom,Html,下面是一个例子: 我有一个DOM对象,$content是从这个div创建的: <div class="content">"test" <!-- m --> <a class="postlink" href="http://imaginethisisareallylongurl.com">http://imagin...longurl.com</a><!-- m --> <img
$content
是从这个div创建的:
<div class="content">"test" <!-- m -->
<a class="postlink" href="http://imaginethisisareallylongurl.com">http://imagin...longurl.com</a><!-- m -->
<img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" /> "test"
<img src="./images/smilies/icon_e_sad.gif" alt=":(" title="Sad" /> sl
<img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" />
<img src="./images/smilies/icon_e_sad.gif" alt=":(" title="Sad" /> ok
</div>
div中的图像标记被其alt属性替换,url被其完整的href
属性替换
我该怎么做
编辑:
大概是这样的:
foreach($content->find('a[class=postlink]') as $postlink)
{
$postlink->outertext = $postlink->href;
}
不起作用。如何在
$contents->innertext
中引用此特定链接,以便修改它?我应该更仔细地阅读文档。您可以自定义解析行为,如下所示:
$html->set_callback('custom_parse');
其中,$html
是您的原始文档
function custom_parse($element)
{
if (isset($element->class)){
if($element->class=='postlink'){
$element->outertext = $element->href;
}
}
if (isset($element->innertext)){
$element->innertext = str_replace('<!-- m -->', '', $element->innertext);
}
if (isset($element->outertext)){
if ($element->tag=='img' and isset($element->alt)){
$element->outertext = $element->alt;
}
}
}
不知道这样做是否“正确”,但它会返回所需的输出。将文本作为dom文档打开,然后解析内部文本。此外,@ColeJohnson您忘记了.com,因此该链接无效
function custom_parse($element)
{
if (isset($element->class)){
if($element->class=='postlink'){
$element->outertext = $element->href;
}
}
if (isset($element->innertext)){
$element->innertext = str_replace('<!-- m -->', '', $element->innertext);
}
if (isset($element->outertext)){
if ($element->tag=='img' and isset($element->alt)){
$element->outertext = $element->alt;
}
}
}
function parse_content($content)
{
$content = $content->innertext;
$content = strip_tags($content);
$content = html_entity_decode($content);
return $content;
}