php - 正则表达式仅按最后一个空白字符拆分字符串

标签 php regex string split

希望这应该是一个快速和简单的方法,使用 PHP 我试图将一个字符串拆分成一个数组,但仅通过最后一个空格实例。到目前为止,我...

$str="hello this is     a    space";
$arr=preg_split("/\s+/",$str);
print_r($arr);

Array ( [0] => hello [1] => this [2] => is [3] => a [4] => space ) 

...由所有空白实例分割。

如何扩展此正则表达式以仅按最后一个空格实例进行拆分?成为……

Array ( [0] => hello this is     a [1] => space ) 

提前感谢您的帮助!

最佳答案

尝试:

$arr=preg_split("/\s+(?=\S*+$)/",$str);

编辑

一个简短的解释:

(?= ... ) 被称为正 look ahead .例如,a(?=b) 将仅匹配单个 'a' 如果下一个字符(它右边的那个)是 ' b'。请注意,'b' 不是匹配的一部分!

\S 只是 character class 的简写[^\s]。换句话说:它匹配除空白字符以外的单个字符。 * 之后的+ 使字符类\S possessive .

最后,$ 表示字符串的结尾。

回顾一下,完整的正则表达式 \s+(?=\S*+$) 将用简单的英语读作如下:

match one or more white space characters only when looking ahead of those white space characters zero or more characters other than white space characters, followed by the end of the string, can be seen.

关于php - 正则表达式仅按最后一个空白字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1530883/

相关文章:

php - 使用 MonologBu​​ndle 自定义 HandlerWrapper

javascript 交换和替换字符串

c - 如何在 C 中仅提取此字符串的一部分?

ios - 如何使用 nsrange 从具有 emoj 的字符串中获取某些部分

Python - 使用 ""分割字符串

string - 在文本中查找字典字符串的最快方法

php - Zend 框架中的日历

HTML value 属性内的 PHP 代码

php - 从数组中删除重复的 strlen 项?

ruby - 使用正则表达式拒绝数组中的项目的语法