php - 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];
?>
解决方案
要使您的代码正常工作,您只需将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];
输出:
練馬春日町Ⅳ
推荐阅读
- django - 在 Django 的选择中显示奇怪的数据
- javascript - 使用 ngx-print 打印图像的问题
- php - Google Cloud Console 虚拟机实例上的 Apache 服务器
- python - 如何修复此 python %s 占位符排列
- android - OnEditorActionListener 中的 requestFocus()
- javascript - 是否可以在 javascript 函数中从 var 中创建具有纬度和经度的 Google 地图中具有位置名称的 var?
- wordpress - 如何在不添加更多 vNIC 或破坏 VM 的情况下创建 GCloud LXD 桥接设备?
- javascript - Rails 动态 grouped_collection_select 自动改变
- linux - 如何使用tail和head在配置文件中的一行之前显示5行
- reactjs - 如何在组件标题中使用翻译?