w3resource

PHP Regular Expression Exercises: Remove the last word from a string


2. Remove the last word from a string

Write a PHP script that removes the last word from a string.

Sample string : 'The quick brown fox'

Visual Presentation:

PHP Regular Expression Exercise: Remove the last word from a string

Sample Solution:

PHP Code:

<?php
// Define the input string
$str1 = 'The quick brown fox';

// Use preg_replace function to remove the last word along with its trailing spaces
echo preg_replace('/\W\w+\s*(\W*)$/', '$1', $str1)."\n";
?>

Output:

The quick brown

Explanation:

In the exercise above,

  • '$str1' variable stores the input string: 'The quick brown fox'.
  • The "preg_replace()" function performs regular expression-based string replacement.
  • The regular expression pattern /\W\w+\s*(\W*)$/ is applied to the input string:
    • \W: Matches any non-word character (e.g., punctuation).
    • \w+: Matches one or more word characters.
    • \s*: Matches zero or more whitespace characters.
    • (\W*)$: Captures zero or more non-word characters at the end of the string.
  • The replacement string '$1' is used to replace the matched pattern with the captured group '$1', which represents the trailing non-word characters.
  • The modified string is then echoed.

Flowchart :

Flowchart: Remove the last word from a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to remove the last *n* words from a string and return the shortened version.
  • Write a PHP function to remove the last word from a string only if it ends with a punctuation mark.
  • Write a PHP script to remove the last word from a string and return it separately along with the trimmed string.
  • Write a PHP function to remove the last word from a string while preserving leading/trailing whitespace and punctuation.

Go to:


PREV : Check if a string contains another string.
NEXT : Remove whitespaces from a string.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.