問題描述
我在 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('/wei?/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
和 這樣的標準類簡寫也不是 Unicode-知道的.您只需要使用 Unicode 速記,正如您所研究的那樣,但是您可以通過使用環顧而不是交替來使它不那么難看:
Even in UTF-8 mode, standard class shorthands like w
and 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.
這篇關于utf-8中的php正則表達式單詞邊界匹配的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!