phpstringreplace

Remove the last word from a string


How can I get a string without its last word using PHP?

For example given the string Hi, I'm Gian Marco I'm looking for Hi, I'm Gian.


Solution

  • try with this :

    $txt = "Hi, I'm Gian Marco";
    $str= preg_replace('/\W\w+\s*(\W*)$/', '$1', $txt);
    echo $str
    

    out put

    Hi, I'm Gian