sam sam - 1 year ago 70
PHP Question

replace all occurences of a string

I want to add a class to all

tags that contain arabic text in it. For example:

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

should become

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

I am trying to use PHP
function to match the pattern (arabic) with following expression:

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

However it is not working properly. It has two problems:

  1. It only matches the first paragraph.

  2. Adds an empty

Sandbox Link

Answer Source

It only matches the first paragraph.

This is because you added the last argument, indicating you want only to replace the first occurrence. Leave that argument out.

Adds an empty <p>.

This is in fact the original <p> which you did not match. Just add it to the matching pattern, but keep it outside of the matching group, so it will be left out when you replace with $1.

Here is a corrected version, also on sandbox:

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