TECH / Servers & Websites 2 min read

How to Get the First or Last Two Characters of a String in PHP

Antonio NEMCD Author
Published Mar 29, 2012 · 2 min

Grabbing the first two – or last few – characters of a string is an everyday PHP task when working with language codes, prefixes, or file extensions. For plain ASCII letters and digits, built-in substr() does the job, while multibyte UTF-8 text requires mb_substr().

PHP logo

Here are concise working examples for both cases so you never accidentally corrupt accented or non-Latin characters.

First and Last 2 Characters: ASCII & Latin Text (substr)

substr($string, $offset, $length) takes the source string, a zero-based starting offset, and the length to return. For example, pulling the two-letter language code from a session locale:

$lang = substr($_SESSION['language_code'], 0, 2); // "en_US" -> "en"

To grab the last two characters instead, pass a negative offset -2 and omit the length argument:

$rez = substr($_SESSION['language_code'], -2); // "en_US" -> "US"

Note that string array keys must always be quoted in modern PHP ($_SESSION['language_code']) – unquoted keys used to emit a notice and throw a fatal error in PHP 8.

UTF-8, Accented Letters, Cyrillic, and Emoji (mb_substr)

Standard substr() counts bytes, not characters. In UTF-8, accented letters, Cyrillic, CJK characters, and emoji take 2 to 4 bytes each – so substr('Привет', 0, 2) returns only one letter, and cutting an odd byte length splits a character in half into a broken replacement symbol.

For any user-facing or multilingual text, use mb_substr() from the mbstring extension:

$firstTwo = mb_substr('Привет', 0, 2, 'UTF-8'); // returns "Пр"
$lastTwo  = mb_substr('Привет', -2, null, 'UTF-8'); // returns "ет"

Whenever you aren’t 100% certain a string is strictly ASCII – names, titles, search queries – reaching straight for mb_substr() saves you from subtle encoding bugs down the road.

Related posts:

Leave a Comment