Skip to content Skip to sidebar Skip to footer

Count Html Links In A String And Add A List

I store the content of a website in a string $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

Solution 1:

require_once("simple_html_dom.php");

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

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

foreach ( $linksas$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>";

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

Solution 2:

Use a DOM Parser

Example:

$h = str_get_html($html);

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

foreach ( $h->find('a') as$a ){
    //print every link ending in .odfif ( ends_with(strtolower($a->href), '.odf') ){ //ends with isn't a function, but it is trivial to writeecho'<li><a href="'.$a->href.'">'.$a->innertext.'</a></li>';
    }
}

Solution 3:

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

Post a Comment for "Count Html Links In A String And Add A List"