Подсчитайте html-ссылки в строке и добавьте список - PullRequest
0 голосов
/ 19 февраля 2010

Я храню содержимое сайта в виде строки $ html .

Я хочу считать все ссылки html, которые ссылаются на файл в формате .otf , добавить список этих ссылок в конец $ html и удалить исходные ссылки.

Пример:

<?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>'
?>        

Как мне это сделать? Стоит ли использовать регулярные выражения или есть другой способ?

Ответы [ 3 ]

5 голосов
/ 19 февраля 2010
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/

2 голосов
/ 19 февраля 2010

Использование DOM Parser

Пример:

$h = str_get_html($html);

$linkCount = count($h->find('a'));

foreach ( $h->find('a') as $a ){
    //print every link ending in .odf
    if ( ends_with(strtolower($a->href), '.odf') ){ //ends with isn't a function, but it is trivial to write

        echo '<li><a href="'.$a->href.'">'.$a->innertext.'</a></li>';
    }
}
0 голосов
/ 19 февраля 2010
preg_match('~<a href="[^"]+\.otf">.*?</a>~s', $html_input, $matches);
$linksCount = count($matches[0]);
preg_replace('~<a href="[^"]+\.otf">.*?</a>~s', '', $html_input);
$html_input.='<ul><li>'.implode('</li><li>', $matches[0]).'</li></ul>';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...