preg_match all paragraphs in a string

我只是一个虾纸丫 提交于 2019-12-02 04:09:22

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!