php regf utf-8中的单词边界匹配 [英] php regex word boundary matching in utf-8

查看:70
本文介绍了php regf utf-8中的单词边界匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在utf-8 php文件中有以下php代码:

I have the following php code in a utf-8 php file:

var_dump(setlocale(LC_CTYPE, 'de_DE.utf8', 'German_Germany.utf-8', 'de_DE', 'german'));
var_dump(mb_internal_encoding());
var_dump(mb_internal_encoding('utf-8'));
var_dump(mb_internal_encoding());
var_dump(mb_regex_encoding());
var_dump(mb_regex_encoding('utf-8'));
var_dump(mb_regex_encoding());
var_dump(preg_replace('/\bweiß\b/iu', 'weiss', 'weißbier'));

我希望最后一个正则表达式仅替换完整的单词,而不替换单词的一部分.

I would like the last regex to replace only full words and not parts of words.

在我的Windows计算机上,它返回:

On my windows computer, it returns:

string 'German_Germany.1252' (length=19)
string 'ISO-8859-1' (length=10)
boolean true
string 'UTF-8' (length=5)
string 'EUC-JP' (length=6)
boolean true
string 'UTF-8' (length=5)
string 'weißbier' (length=9)

在网络服务器(Linux)上,我得到:

On the webserver (linux), I get:

string(10) "de_DE.utf8"
string(10) "ISO-8859-1"
bool(true)
string(5) "UTF-8"
string(10) "ISO-8859-1"
bool(true)
string(5) "UTF-8"
string(9) "weissbier"

因此,正则表达式可以在Windows上正常运行,但不能在linux上运行.

Thus, the regex works as I expected on windows but not on linux.

所以主要问题是,我应该如何编写仅在单词边界匹配的正则表达式?

So the main question is, how should I write my regex to only match at word boundaries?

第二个问题是如何让Windows知道我想在php应用程序中使用utf-8.

A secondary questions is how I can let windows know that I want to use utf-8 in my php application.

推荐答案

即使在UTF-8模式下,诸如\w\b的标准类速记也不支持Unicode.您只需要使用Unicode速记法即可,但是可以通过使用环视而不是交替来使它看起来不那么难看:

Even in UTF-8 mode, standard class shorthands like \w and \b are not Unicode-aware. You just have to use the Unicode shorthands, as you worked out, but you can make it a little less ugly by using lookarounds instead of alternations:

/(?<!\pL)weiß(?!\pL)/u

还请注意我如何将花括号放在Unicode类的简写形式之外;当类名由单个字母组成时,您可以这样做.

Notice also how I left the curly braces out of the Unicode class shorthands; you can do that when the class name consists of a single letter.

这篇关于php regf utf-8中的单词边界匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆