替换所有出现的字符串

replace all occurrences of a string

我想将 class 添加到所有包含阿拉伯语文本的 p 标签。例如:

<p>لمبارة وذ</p> 
<p>do nothing</p> 
<p>خمس دقائق يخ</p> 
<p>مراعاة إبقاء 3 لاعبين</p>

应该变成

<p class="foo">لمبارة وذ</p> 
<p>do nothing</p>
<p class="foo">خمس دقائق يخ</p> 
<p class="foo">مراعاة إبقاء 3 لاعبين</p>

我正在尝试使用 PHP preg_replace 函数将模式(阿拉伯语)与以下表达式匹配:

preg_replace("~(\p{Arabic})~u", "<p class=\"foo\">", $string, 1);

但是它不能正常工作。它有两个问题:

  1. 它只匹配第一段。
  2. 添加一个空 <p>.

沙盒Link

It only matches the first paragraph.

这是因为您添加了最后一个参数,表明您只想替换第一个参数。把那个论点放在一边。

Adds an empty <p>.

这实际上是您未匹配的原始 <p>。只需将它添加到匹配模式中,但将其保留在匹配组之外,因此当您替换为 </code>.</p> 时它将被排除在外 <p>这是更正后的版本,也在 <a href="http://sandbox.onlinephpfunctions.com/code/747ba3b5676602ba4d0aea787d7d0fb1457b3ffd" rel="nofollow">sandbox</a>:</p> <pre><code>$text = preg_replace("~<p>(\p{Arabic}+)~u", "<p class=\"foo\">", $string);

你的第一个问题是你没有告诉它匹配 <p>,所以它没有。

您的主要问题是空格不是阿拉伯语。只需添加替代方案以匹配它们即可解决您的问题:

$text = preg_replace("~<p>(\p{Arabic}*|\s*)~u", "<p class=\"foo\">", $string);

使用 DOMDocument 和 DOMXPath:

$html = <<<'EOD'
<p>لمبارة وذ</p> 
<p>خمس دقائق يخ</p> 
<p>مراعاة إبقاء 3 لاعبين</p>
EOD;

libxml_use_internal_errors(true);

$dom = new DOMDocument;
$dom->loadHTML('<div>'.$html.'</div>', LIBXML_HTML_NOIMPLIED);

$xpath = new DOMXPath($dom);

// here you register the php namespace and the preg_match function
// to be able to use it in the XPath query
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPhpFunctions('preg_match');

// select only p nodes with at least one arabic letter
$pNodes = $xpath->query("//p[php:functionString('preg_match', '~\p{Arabic}~u', .) > 0]");

foreach ($pNodes as $pNode) {
    $pNode->setAttribute('class', 'foo');
}

$result = '';
foreach ($dom->documentElement->childNodes as $childNode) {
    $result .= $dom->saveHTML($childNode);
}

echo $result;