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\"
.
You can do it with regular expression. (see answer of Ahmed Ziani.)
However, in PHP you can also do it using some inbuilt function. see the code below
$text = "Hi, I'm Gian Marco";
$last_space_position = strrpos($text, ' ');
$text = substr($text, 0, $last_space_position);
echo $text;
The regular exprerssion can cause issues when the string has special characters. Why not simply go with this:
$input = "Hi, I'm Gian Marco";
$output = substr($input, 0, strrpos($input, " "));
echo $output;
This code may help you :
$str="Hi, I'm Gian Marco";
$split=explode("",$str);
$split_rem=array_pop($split);
foreach ($split as $k=>$v)
{
echo $v.'';
}
The current solution is ok if you do not know the last word and the string length is short.
In case you do know it, for instance when looping a concat string for a query like this:
foreach ($this->id as $key => $id) {
$sql.=' id =' . $id . ' OR ';
}
A better solution:
$sql_chain = chop($sql_chain," OR ");
Be aware that preg_replace with a regex is VERY slow with long strings. Chop is 100 times faster in such case and perf gain can be substantial.
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
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