preg_match all paragraphs in a string

前端 未结 2 1495
情书的邮戳
情书的邮戳 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: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:

    para 1

    نص عربي أو فارسي

    para3

    "; $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.

提交回复
热议问题