如何在 PHP 中使用 preg_replace 匹配俄语单词?

发布于 2024-10-13 13:30:53 字数 2879 浏览 3 评论 0原文

如何在 PHP 中匹配字符串(也是俄语)中的俄语单词?

例如,像这样的事情:

$pattern = '/слово/';
preg_replace($pattern, $replacement, $string_in_russian)

我尝试了 utf8_encodehtmlentities 以及 $pattern 的 UTF-8 标志,但它不起作用。我还应该对 $string_in_ Russian 进行编码吗?

更新: /u 标志的建议不起作用,因此我放置了我需要的实际代码。它来自 Wordpress 的词汇表插件(我的网站已正确设置为使用俄语,并且它确实有效,但在本例中不起作用)。所以这是代码

$glossary_title = $glossary_item->post_title;
$glossary_search = '/\b'.$glossary_title.'s*?\b(?=([^"]\*"[^"]\*")\*[^"]*$)/iu';
$glossary_replace = '<a'.$timestamp.'>$0</a'.$timestamp.'>';
$content_temp = preg_replace($glossary_search, $glossary_replace, $content, 1);

当我对 HTML 注释进行快速回显时,这就是我得到的模式字符串
/\bсловоs*?\b(?=([^"]*"[^"]")[^"]*$)/iu

那么,似乎仍然不起作用。我想也许是“s”把我搞砸了(这个级别的正则表达式有点超出了我的范围,但我认为它是可能的复数),但删除它并没有帮助。

更新#2:好吧,所以我决定做一个完整的“空白石板”测试 - 纯 PHP 文件,其中包含一些英语和俄语的 $content 字符串以及要替换的目标单词,这是代码

$content_en = 'Nulla volutpat pretium nunc, ac feugiat neque lobortis vitae. In eu sapien sit amet eros tincidunt viverra. <b style="color:purple">Proin</b> congue hendrerit felis, et consequat neque ultrices lobortis. <b style="color:purple">Proin</b> luctus bibendum libero et molestie. Sed tristique lacus a urna semper eget feugiat lacus varius. Donec vel sodales diam. <b style="color:purple">Proin</b> fringilla laoreet purus, a facilisis nisi porttitor vel. Nullam ac justo ac elit laoreet ullamcorper vel a magna. Suspendisse in arcu sapien.';
$find_en = 'proin';
$replace_with_en = '<em style="color:red">REPLACEMENT</em>';
$glossary_search = '/\b'.$find_en.'s*?\b(?=([^"]*"[^"]*")*[^"]*$)/iu';
$content_en_replaced = preg_replace($glossary_search, $replace_with_en, $content_en);

$content_ru = 'Lorem Ipsum используют потому, что тот обеспечивает более или менее стандартное заполнение шаблона, а также реальное распределение букв и пробелов в абзацах, которое не получается при простой дубликации "Здесь <b style="color:purple">ваш</b> текст.. Здесь <b style="color:purple">ваш</b> текст.. Здесь <b style="color:purple">ваш</b> текст.." Многие программы электронной вёрстки и редакторы HTML используют Lorem Ipsum в качестве текста по умолчанию.';
$find_ru = 'ваш';
$replace_with_ru = '<em style="color:red">Многие</em>';
$glossary_search = '/\b'.$find_ru.'s*?\b(?=([^"]*"[^"]*")*[^"]*$)/iu';
$content_ru_replaced = preg_replace($glossary_search, $replace_with_ru, $content_ru);

,这是。输出的屏幕截图 http://www.flickr.com/photos/iliadraznin/5372578707/< /a>

正如您所看到的,英语文本已替换目标单词,而俄语文本则没有,并且代码相同,并且我使用 /u 标志。该文件也是 UTF-8 编码的。(有什么建议吗?再次,我尝试删除“s”,仍然没有)

How do I go about matching a Russian word in a string (also in Russian) in PHP?

So for example something like this:

$pattern = '/слово/';
preg_replace($pattern, $replacement, $string_in_russian)

I tried utf8_encode and htmlentities with UTF-8 flag for $pattern, but it didn't work. Should I also encode $string_in_russian?

Update: Suggestion for /u flag didn't work so I'm putting the actual code I need this for. It is from a glossary plugin for Wordpress (my site is properly setup to use Russian language, and it does work, but not in this instance). So here's the code

$glossary_title = $glossary_item->post_title;
$glossary_search = '/\b'.$glossary_title.'s*?\b(?=([^"]\*"[^"]\*")\*[^"]*$)/iu';
$glossary_replace = '<a'.$timestamp.'>$0</a'.$timestamp.'>';
$content_temp = preg_replace($glossary_search, $glossary_replace, $content, 1);

When I do a quick echo into HTML comment this is the kind of string I get for the pattern
/\bсловоs*?\b(?=([^"]*"[^"]")[^"]*$)/iu

And well, that still doesn't seem to work. I thought maybe it was the "s" that was screwing me over (this level of regex is a bit beyond me but I assume it's there for possible plurals), but removing it didn't help.

Update #2: Okay so I decided to do a complete "blank slate" test - plain PHP file with some $content strings in English and Russian and target words to replace. Here is the code

$content_en = 'Nulla volutpat pretium nunc, ac feugiat neque lobortis vitae. In eu sapien sit amet eros tincidunt viverra. <b style="color:purple">Proin</b> congue hendrerit felis, et consequat neque ultrices lobortis. <b style="color:purple">Proin</b> luctus bibendum libero et molestie. Sed tristique lacus a urna semper eget feugiat lacus varius. Donec vel sodales diam. <b style="color:purple">Proin</b> fringilla laoreet purus, a facilisis nisi porttitor vel. Nullam ac justo ac elit laoreet ullamcorper vel a magna. Suspendisse in arcu sapien.';
$find_en = 'proin';
$replace_with_en = '<em style="color:red">REPLACEMENT</em>';
$glossary_search = '/\b'.$find_en.'s*?\b(?=([^"]*"[^"]*")*[^"]*$)/iu';
$content_en_replaced = preg_replace($glossary_search, $replace_with_en, $content_en);

$content_ru = 'Lorem Ipsum используют потому, что тот обеспечивает более или менее стандартное заполнение шаблона, а также реальное распределение букв и пробелов в абзацах, которое не получается при простой дубликации "Здесь <b style="color:purple">ваш</b> текст.. Здесь <b style="color:purple">ваш</b> текст.. Здесь <b style="color:purple">ваш</b> текст.." Многие программы электронной вёрстки и редакторы HTML используют Lorem Ipsum в качестве текста по умолчанию.';
$find_ru = 'ваш';
$replace_with_ru = '<em style="color:red">Многие</em>';
$glossary_search = '/\b'.$find_ru.'s*?\b(?=([^"]*"[^"]*")*[^"]*$)/iu';
$content_ru_replaced = preg_replace($glossary_search, $replace_with_ru, $content_ru);

And here is a screenshot of the output http://www.flickr.com/photos/iliadraznin/5372578707/

As you can see the English text had the target word replaced, while the Russian hasn't and the code is identical and I'm using the /u flag. The file is also UTF-8 encoded. Any suggestions? (and again, I tried removing the "s", still nothing)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

缪败 2024-10-20 13:30:53

如果您进行真正的空白测试,您会发现俄语没有任何问题 - 实际上是单词边界方面破坏了正则表达式。

$glossary_search = '/'.$find_ru.'/iu'; // Works fine
$glossary_search = '/\b'.$find_ru.'\b/iu'; // Breaks

单词边界简写不支持 UTF-8,因此,根据这个问题: php 正则表达式 utf-8 中的单词边界匹配 您可以尝试以下操作:

$glossary_search = '/(?<!\pL)'.$find_ru.'(?!\pL)/iu';

在我的测试中效果很好。

If you do a real blank slate test, you will find there's nothing wrong with the Russian - it's actually the word boundary aspect that is breaking the regex.

$glossary_search = '/'.$find_ru.'/iu'; // Works fine
$glossary_search = '/\b'.$find_ru.'\b/iu'; // Breaks

Word boundary shorthand is not UTF-8 aware, so, per this question: php regex word boundary matching in utf-8 you can try the following:

$glossary_search = '/(?<!\pL)'.$find_ru.'(?!\pL)/iu';

That works fine on my test here.

骑趴 2024-10-20 13:30:53

对于初学者,您必须确保您的 php 文件是使用 UTF-8 编码的。即使文件中没有任何 UTF-8 字符(它们可能是从另一个文件传入的),文件也必须是 UTF-8,文件内部的函数才能使用 UTF-8。

For starters, you must make sure that your php file is encoded with UTF-8. Even if you do not have any UTF-8 characters in the file (they might be passed in from another file), the file must be UTF-8 for functions inside of it to work with UTF-8.

别念他 2024-10-20 13:30:53

PCRE 正则表达式中的“u”选项提供 Unicode,因此:

<?php
  $str = 'тест бла бла бла';
  if(preg_match("'тест'isu", $str, $match))
  {
    echo $match;
  }
?>

另外,preg_replace 的示例:

<?php
  $str = 'тест бла бла бла';
  echo preg_replace("'бла'isu", '', $str);
?>

"u" option in PCRE regexp's provides Unicode, so:

<?php
  $str = 'тест бла бла бла';
  if(preg_match("'тест'isu", $str, $match))
  {
    echo $match;
  }
?>

Also, example for preg_replace:

<?php
  $str = 'тест бла бла бла';
  echo preg_replace("'бла'isu", '', $str);
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文