Search code examples
phphtml-parsing

How to parsing some html tags content and separate them by some sepecial chars like "|"?


I have a variable like:

$content = '
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/digital_marketing">digital marketing</a>
</i>
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/seo">seo</a>
</i>
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/internet_marketing">internet marketing</a>
</i>';

how to extract a tags content like this: digital marketing|seo|internet marketing

Thank You.


Solution

  • All the content which you are trying to access is present in a tag which just the child of i. Here i am using DOMDocument to achieve desired result.

    Try this code snippet here

    <?php
    
    ini_set('display_errors', 1);
    $string=<<<HTML
    <i class="fa fa-hashtag" aria-hidden="true">
        <a href="http://example.com/tag/digital_marketing">digital marketing</a>
    </i>
    <i class="fa fa-hashtag" aria-hidden="true">
        <a href="http://example.com/tag/seo">seo</a>
    </i>
    <i class="fa fa-hashtag" aria-hidden="true">
        <a href="http://example.com/tag/internet_marketing">internet marketing</a>
    </i> 
    HTML;
    $domDocument = new DOMDocument();
    $domDocument->loadHTML($string);
    
    $domXPath = new DOMXPath($domDocument);
    $results = $domXPath->query("//i/a");
    foreach($results as $result)
    {
        $data[]= $result->textContent;
    }
    echo implode("|",$data);