Home > Blockchain >  Removing link from Unordered list as string in array
Removing link from Unordered list as string in array

Time:12-16

Using PHP, I would like to remove all the links in an unordered list and put them in an array. So the output would be: array[0]='<a href="#">Benefits</a>', array[1]='<a href="#">Cost Savings</a>', etc.

<ul>
<li><a href="#">Benefits</a></li>
<li><a href="#">Cost Savings</a></li>
<li><a href="#">Member listing</a></li>
</ul>

Using; preg_match_all('/<a href=\"(.*?)\"[.*]?>(.*?)<\/a>/i', $content, $matches);

I get:

array(3) { [0]=> array(3) { [0]=> string(24) "Benefits" [1]=> string(28) "Cost Savings" [2]=> string(30) "Member listing" } [1]=> array(3) { [0]=> string(1) "#" [1]=> string(1) "#" [2]=> string(1) "#" } [2]=> array(3) { [0]=> string(8) "Benefits" [1]=> string(12) "Cost Savings" [2]=> string(14) "Member listing" } }

But i need to put it into one array.

CodePudding user response:

To fetch the links you can leverage domdocument and domxpath

    $html = '<html><body><ul>
    <li><a href="#">Benefits</a></li>
    <li><a href="#">Cost Savings</a></li>
    <li><a href="#">Member listing</a></li>
    </ul></body></html>';

    $dom = new DOMDocument();
    $dom->loadHTML( $html ); // loads the html into the class

    $xpath = new DOMXPath( $dom );
    $items = $xpath->query('*/ul/li/a'); // matches any elements in this order
    $array = array();
    foreach( $items as $item )
    {
        $array[] = $dom->saveHTML( $item ); // using the parent document, get just a single elements html
    }

    // Array
    // (
    //     [0] => <a href="#">Benefits</a>
    //     [1] => <a href="#">Cost Savings</a>
    //     [2] => <a href="#">Member listing</a>
    // )
  •  Tags:  
  • php
  • Related