Skip to content

All topics  /  PHP

PHP Remove Last Word from String Example

PHP ·

Hi Dev,

In this post, we will learn php remove last word from string example. I explained simply about how to remove last word from string in php?. it's simple example of remove last word from string in php example. I would like to show you how to use function to remove last word from string in php? .

There are tow example to remove last word from strings in PHP. in this example, we will use to substr() and preg_replace() function to remove last word. so Let's both the following example with output.

Example 1: Remove Last Word from String


index.php

<?php  	

   
   $str ='Hi, I an Experts PHP';
   // Remove Last Word from String  
   $result = substr($str, 0, strrpos($str, " "));
   echo $result;

   
?>

Output:

Hi, I an Experts

Example 2: Remove Last Word from String

index.php

<?php    

   
   $str ='Hello Nicesnippets .com';
   // Remove Last Word from String
   $result = preg_replace('~\\s+\\S+$~', '', $str);
   echo $result;

   
?>

Output:

Hello Nicesnippets

I hope it could help you...