Removing last characters from the string

Remove characters from the end of a string

Use substr() with a negative length when you need to remove a known number of trailing bytes. Check the input assumptions first when strings may be empty or contain multibyte characters.

$value = 'invoice.csv';$withoutLastFour = substr($value, 0, -4);echo $withoutLastFour; // invoice

When the length is unknown, use a negative length with substr(). This operates on bytes, not Unicode characters. For multibyte text, use mb_substr() when the mbstring extension is available.

$q = 'sample-text';$q = substr($q, 0, -3);echo $q; // sample-t

Do not build SQL by appending user input and trimming a trailing comma. The query below uses placeholders so the values can be bound as parameters:

SELECT * FROM table_name WHERE student_id IN (?, ?, ?, ?)
$ids = [1, 2, 3, 4];$placeholders = implode(', ', array_fill(0, count($ids), '?'));$sql = 'SELECT * FROM table_name WHERE student_id IN (' . $placeholders . ')';// Prepare $sql and pass $ids to execute(); never append untrusted IDs to SQL.

If your goal is only to format comma-separated data, implode() avoids generating a trailing comma in the first place:

$items = ['1', '2', '3', '4'];$list = implode(',', $items);echo $list; // 1,2,3,4 (data formatting only, not SQL parameters)

See implode() for joining values, and substr() for slicing.

Example 2: Extracting the Last 4 Characters of a String

We can easily extract the last few characters of a string using substr() by providing a negative offset:

$string = "Hello, World!";$last_chars = substr($string, -4);echo $last_chars; // rld!

Example 3: Extracting the Last Word from a Sentence

This example demonstrates extracting the last word from a sentence using strrpos() and substr():

$sentence = 'PHP is a popular scripting language';$position = strrpos($sentence, ' ');$last_word = $position === false ? $sentence : substr($sentence, $position + 1);echo $last_word; // language

Example 4: Removing the Last Character Conditionally

You can remove the last character only if it is a specific value (e.g., period):

$sentence = 'This is a sentence.';if (str_ends_with($sentence, '.')) { // PHP 8+
    $sentence = substr($sentence, 0, -1);}echo $sentence; // This is a sentence

String Functions More substr() examples Join values without trailing delimiters


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer