How can I remove, with PHP, the last word from a String?
For example the string "Hi, I'm Gian Marco"
would become "Hi, I'm Gian"
.
Use: var str = "I want to remove the last word."; var lastIndex = str. lastIndexOf(" "); str = str. substring(0, lastIndex);
You can use the PHP substr_replace() function to remove the last character from a string in PHP. $string = "Hello TecAdmin!"; echo "Original string: " . $string .
After getting the position of last occurring space we can easily get the last word in the string using the substr() function and store this in a new string variable. At last, we can use the strlen() function to find the length of the last word in the string.
PHP Code: <? php $str1 = 'The quick brown fox'; echo preg_replace('/\W\w+\s*(\W*)$/', '$1', $str1).
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
check this
<?php
$str ='"Hi, I\'m Gian Marco" will be "Hi, I\'m Gian"';
$words = explode( " ", $str );
array_splice( $words, -1 );
echo implode( " ", $words );
?>
source : Remove last two words from a string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With