Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How can I remove from String the last word?

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".

like image 944
Kiuki Avatar asked Apr 03 '15 08:04

Kiuki


People also ask

How do I remove the last word from a string?

Use: var str = "I want to remove the last word."; var lastIndex = str. lastIndexOf(" "); str = str. substring(0, lastIndex);

How do I remove the last letter from a word in PHP?

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 .

How can I get the last word of a string in PHP?

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.

Which script can you use in a regular expression in PHP to remove the last word from a string?

PHP Code: <? php $str1 = 'The quick brown fox'; echo preg_replace('/\W\w+\s*(\W*)$/', '$1', $str1).


2 Answers

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
like image 87
Ahmed Ziani Avatar answered Sep 24 '22 05:09

Ahmed Ziani


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

like image 42
Sameed Alam Qureshi Avatar answered Sep 22 '22 05:09

Sameed Alam Qureshi