Regex to split a string only by the last whitespace character

后端 未结 3 1789
清酒与你
清酒与你 2021-02-07 19:33

hopefully this should be a quick and simple one, using PHP I\'m trying to split a string into an array but by only the last instance of whitespace. So far I have...



        
3条回答
  •  伪装坚强ぢ
    2021-02-07 19:52

    Try:

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

    Edit

    A short explanation:

    The (?= ... ) is called a positive look ahead. For example, a(?=b) will only match a single 'a' if the next character (the one to the right of it) is a 'b'. Note that the 'b' is not a part of the match!

    The \S is just a short-hand for the character class [^\s]. In other words: it matches a single character other than a white space character. The + after the * makes the character class \S possessive.

    Finally, the $ denotes the end of the string.

    To recap, the complete regex \s+(?=\S*+$) would read in plain English as follows:

    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.

提交回复
热议问题