Regex to split a string only by the last whitespace character

后端 未结 3 1793
清酒与你
清酒与你 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:36

    This should work:

    $str="hello this is a  space";
    
    preg_match('~^(.*)\s+([^\s]+)$~', $str, $matches);
    $result = array($matches[1], $matches[2]);
    

    You could do it without a regex:

    $parts = array_map('trim', explode(' ', $str));
    $result = array(
        implode(' ', array_slice($parts, 0, -1)),
        end($parts)
    );
    

    or

    $lastSpace = strrpos($str, ' ');
    $str1 = trim(substr($str, 0, $lastSpace));
    $str2 = trim(substr($str, $lastSpace));
    $result = array( $str1, $str2 );
    

提交回复
热议问题