Skip to content Skip to sidebar Skip to footer

PHP : Extracting String Between Two Tags By Childs Content

I have this following html markup:
  • Online: 2/14/2010 3:40 AM
  • Solution 1:

    I suggest use an HTML Parser here, DOMDocument in particular with xpath.

    Example:

    $markup = '<ul>
        <li>
            <strong>Online:</strong>
            2/14/2010 3:40 AM
        </li>
        <li>
            <strong>Hearing Impaired:</strong>
            No
        </li>
        <li>
            <strong>Downloads:</strong>
            3,840
        </li>
    </ul>';
    
    $dom = new DOMDocument();
    $dom->loadHTML($markup);
    $xpath = new DOMXpath($dom);
    // this just simply means get the string next on that strong tag with a text of Downloads:
    $download = trim($xpath->evaluate("string(//strong[text()='Downloads:']/following-sibling::text())"));
    echo $download; // 3,840
    

    Solution 2:

    Use a html parser for parsing html files. If you insist on regex then you could try the below,

    <li>[^<>]*<strong>Downloads:<\/strong>\s*\K.*?(?=\s*<\/li>)
    

    DEMO

    Code:

    $string = <<<EOT
    <ul>
        <li>
            <strong>Online:</strong>
            2/14/2010 3:40 AM
        </li>
        <li>
            <strong>Hearing Impaired:</strong>
            No
        </li>
        <li>
            <strong>Downloads:</strong>
            3,840
        </li>
    </ul>
    EOT;
    $regex = "~<li>[^<>]*<strong>Downloads:<\/strong>\s*\K.*?(?=\s*<\/li>)~s";
    if (preg_match($regex, $string, $m)) {
        $yourmatch = $m[0]; 
        echo $yourmatch;
        } // 3,840
    

Post a Comment for "PHP : Extracting String Between Two Tags By Childs Content"