首页 > 解决方案 > php第一个单词仅来自mb字符串

问题描述

我使用了 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]; 

?>

小提琴

标签: phppreg-matchpreg-splitmbstring

解决方案


要使您的代码正常工作,您只需将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+它将匹配尽可能多的单词字符,即直到它到达第一个单词中断。

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

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

输出:

練馬春日町Ⅳ

3v4l.org 上的演示


推荐阅读