计算字符串中的html链接并添加列表 [英] Count html links in a string and add a list

查看:134
本文介绍了计算字符串中的html链接并添加列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将网站的内容存储在字符串 $ html 中。

I store the content of a website in a string $html.

我要计数所有链接到 .otf 格式的文件的html链接添加 $ html 结尾和删除原始链接的链接列表。

I want to count all html links that link to a file in the .otf format, add a list of these links to the end of $html and remove the original links.

示例:

<?php
$html_input = '
<p>
    Lorem <a href="font-1.otf">ipsum</a> dolor sit amet, 
    consectetur <a href="http://www.cnn.com">adipiscing</a> elit.
    Quisque <a href="font-2.otf">ultricies</a> placerat massa 
    vel dictum.
</p>'

// some magic here    

$html_output = '
<p>
    Lorem ipsum dolor sit amet, 
    consectetur <a href="http://www.cnn.com">adipiscing</a> elit.
    Quisque ultricies placerat massa 
    vel dictum.
</p>
<p>.otf-links: 2</p>
<ul>
    <li><a href="font-1.otf">ipsum</a></li>
    <li><a href="font-2.otf">ultricies</a></li>
</ul>'
?>        

我如何做?我应该使用正则表达式还是另一种方式?

How do I do that? Should I use regular expressions, or is there another way?

推荐答案

require_once("simple_html_dom.php");

$doc = new simple_html_dom();
$doc->load($input_html);

$fonts = array();
$links = $doc->find("a");

foreach ( $links as $l ) {
    if ( substr($l->href, -4) == ".otf" ) {
        $fonts[]      = $l->outertext;
        $l->outertext = $l->innertext;
    }
}

$output = $doc->save() . "\n<p>.otf-links: " . count($fonts) ."</p>\n" .
    "<ul>\n\t<li>" . implode("</li>\n\t<li>", $fonts) . "</li>\n</ul>";

简单HTML DOM的文档 http://simplehtmldom.sourceforge.net/

Documenation for Simple HTML DOM http://simplehtmldom.sourceforge.net/

这篇关于计算字符串中的html链接并添加列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆