检测 PHP 字符串中的希伯来语字符

Detecting Hebrew Characters in PHP Strings

在 PHP 中,是否有已知的 safe/reliable 方式

  1. 通常检测纯英文字符串中的希伯来语字符。
  2. 用某些东西替换那个字符

我知道我可以,对于一组特定的字符,使用 mb_ereg_replace 来替换特定的字符。但是,我感兴趣的是能够扫描可能包含 any 希伯来字符的字符串,然后将其替换为东西。

也就是说,我可能有两个像这样的字符串

<?php
    $string1 = "Look at this hebrew character: חַ. Isn't it great?";
    $string2 = "Look at this other hebrew character: יַָ. It is also great?";

我想要一个能给我以下字符串的函数

Look at this hebrew character: \texthebrew{ח}. Isn't it great?
Look at this other hebrew character: \texthebrew{י}. It is also great?

理论上我知道我可以在 the hebrew UTF-8 range 中扫描字符串并检测这些字符, 但是 PHP 中字符串的字符编码是如何工作的对我来说总是有点模糊,如果存在这种情况,我宁愿使用 proven/known 解决方案。

mb_ereg_replace_callback function is useful in your case. The regular expression dialect has support for named properties, the Hebrew property specifically. That is Hewbrew Unicode block (IntlChar::BLOCK_CODE_HEBREW).

您需要做的就是屏蔽希伯来文段:

mbregex_encoding('utf-8');
var_dump(mb_ereg_replace_callback('\p{Hebrew}+', function($matches) {
    return vsprintf('\texthebrew{%s}', $matches);
}, $subject));

输出:

string(65) "Look at this hebrew character: \texthebrew{חַ}. Isn't it great?"

如输出所示,具有两个代码点的四个字节正确地包装在一个段中。

我不知道在 PHP 中用这么少的代码还有什么其他方法可以做到这一点。