PHP的第一个单词只从MB字符串

时间:2020-02-19 03:20:50

标签: php preg-match preg-split mbstring

我使用了preg_match,但它返回的pdf是英文,这就是为什么的原因。

但是我只想得到练马春日町Ⅳ

有什么方法可以检测到mb字符串吗?

<?php 
// Initialize a sentence to a variable 
$sentence = '練馬春日町Ⅳ 清掃レポート.pdf'; 

// Use preg_match() function to get the 
// first word of a string 
preg_match('/\b\w+\b/i', $sentence, $result);  

// Display result 
echo "The first word of string is: ".$result[0]; 

?>

FIDDLE

1 个答案:

答案 0 :(得分:1)

要使代码正常工作,您只需要在正则表达式中添加u标志,使其与unicode字符匹配:

preg_match('/^\w+/iu', $sentence, $result);  
echo "\nThe first word of string is: ".$result[0];

输出:

The first word of string is: 練馬春日町Ⅳ

请注意,由于您需要第一个单词,因此可以简单地用^锚定正则表达式,而不需要第二个\b,因为\w+将匹配尽可能多的单词字符,即直到第一个断字。

或者,您可以将mb_split与正则表达式\p{Z}配合使用,该正则表达式与任何unicode空格或不可见分隔符匹配:

$sentence = '練馬春日町Ⅳ 清掃レポート.pdf'; 
$first_word = mb_split('\p{Z}', $sentence);
echo $first_word[0];

输出:

練馬春日町Ⅳ

Demo on 3v4l.org

相关问题