How to Remove Last Word from a String Using PHP?

Hello Friends Today, through this tutorial, I will tell you how to remove the last word of any string value with the help of php.

Friends, I will tell you this solution 2 ways how you can remove the last word of any string value in php.

Example 1:-

<?php
$txt = "Hi, I an Experts PHP";
$str= preg_replace('/\W\w+\s*(\W*)$/', '$1', $txt);
echo $str
?>

 

Example 2:-

<?php
$str ='Hi, I an Experts PHP';
$words = explode( " ", $str );
array_splice( $words, -1 );
echo implode( " ", $words );
?>

array_splice() :- This function is used to insert a new element into an Array or to remove one or more Elements from an Array. When we use this function to remove Elements of an Array, This function then returns an Array Return of the removed Array Elements, which we can use again as a new Array, which contains only those Elements that have been removed from an Array.