Remove Last Two Or Three Words From a String in PHP

How to Remove Last Two Word From a String in PHP, How can I remove from String the last Two word, Remove Last Three Word From a String in PHP, How can I remove from String the last Three word

Hello friends So today I will tell you through these tutorials how to remove the last 2 or 3 words from the value of any string with php. So let’s start.

So first I made a variable and passed the string value in it.And now with the help of some inbuilt php function, we will remove the last 2 words from the string value given in this variable. And together with these php functions, we will know about.

 

How to Remove Last Two Words From a String in PHP

 

<?php
$str = "Hi I am Jyoti Chaurasiya.";
$words = explode( " ", $str );
array_splice( $words, -2 );
echo implode( " ", $words );
?>

 

How to Remove Last Three Words From a String in PHP

 

<?php 
$str = "Hi I am Jyoti Chaurasiya."; 
$words = explode( " ", $str ); 
array_splice( $words, -3 ); 
echo implode( " ", $words ); 
?>

array_splice()

Many times, we need such a need during PHP programming that we can not use any Array as much, but we have to use only a specific portion of that array. In order to fulfill this need we need to divide Array into pieces. To satisfy this need, PHP offers us a function named array_slice ().

impload() Function

This Function Argument accepts an Array and a Connection and returns a Single String Return to that Connector by placing it between every Element of Array. If we do not specify a connector in this Array, then by default PHP uses an Empty String as a connector.

explode() Function

This Function works the Exactly Reverse of the implode () function. This means that the Function divides a Delimiter containing String into several sub-strings based on the delimiter and returns the Array to every sub-string as an Array Element by placing it in Array.