preg_match all paragraphs in a string

前端 未结 2 1494
情书的邮戳
情书的邮戳 2021-01-24 04:12

The following string contains multiple

tags. I want to match the contents of each of the

with a pattern, and if it matches, I want

相关标签:
2条回答
  • 2021-01-24 04:39
    • Create a capture group on the <p> tag
    • Use preg_replace

    https://regex101.com/r/nE5pT1/1

    $str = "<p>para 1</p><p>نص عربي أو فارسي</p><p>para3</p>"; 
    $result = preg_replace("/(<p>)[\\x{0590}-\\x{05ff}\\x{0600}-\\x{06ff}]/u", "<p class=\"foo\">", $str, 1);
    
    0 讨论(0)
  • 2021-01-24 04:41

    Use a combination of SimpleXML, XPath and regular expressions (regex on text(), etc. are only supported as of XPath 2.0).
    The steps:

    1. Load the DOM first
    2. Get all p tags via an xpath query
    3. If the text / node value matches your regex, apply a css class

    This is the actual code:

    <?php
    
    $html = "<html><p>para 1</p><p>نص عربي أو فارسي</p><p>para3</p></html>";
    $xml = simplexml_load_string($html);
    
    # query the dom for all p tags
    $ptags = $xml->xpath("//p");
    
    # your regex
    $regex = '~[\x{0590}-\x{05ff}\x{0600}-\x{06ff}]~u';
    
    # alternatively:
    # $regex = '~\p{Arabic}~u';
    
    # loop over the tags, if the regex matches, add another attribute
    foreach ($ptags as &$p) {
        if (preg_match($regex, (string) $p))
            $p->addAttribute('class', 'some cool css class');
    }
    
    # just to be sure the tags have been altered
    echo $xml->asXML();
    
    ?>
    

    See a demo on ideone.com. The code has the advantage that you only analyze the content of the p tag, not the DOM structure in general.

    0 讨论(0)
提交回复
热议问题