Categories
PHP

Extract a specific portion of string by position

Use the substr() function to extract a portion of a string. Use mb_substr() function instead if you are dealing with a multibyte string.

substr()

substr(string $string, int $offset, ?int $length = null): string
  • $string the input string
  • $offset the starting position (a negative or positive number)
  • $length the length to extract (a negative or positive number)

The substr function returns the extracted part of the input string or an empty string (before the PHP 8.0.0, false was returned).

To fetch a part of a string, provide a string ($string) and the position ($offset) of the first character to be extracted (note: the first character has the index 0 in a string). From this character on, the rest of the string is returned.

How to extract a part of string:

<?php
 //      0123456789
 $str = 'My site is BrainBell.com';
 echo substr($str, 11);
 //BrainBell.com

If you only want to return a part of it, provide the length ($length) in the third parameter. The following code extracts BrainBell:

<?php
 $str = 'My site is BrainBell.com';
 echo substr($str, 11, 9);
 //BrainBell

If a negative position ($offset) is passed, the starting point of the returned string is counted from the end of the input string.

How to extract the last character(s) from a string:

<?php
 //                    9876543210
 $str = 'My site is BrainBell.com';
 echo substr($str, -13);
 //BrainBell.com

 echo substr($str, -13, 9);
 //BrainBell

If the $length is negative, for example -4, the last 4 characters will not be part of the result. The following examples show how negative $length can be used:

<?php
 $str = 'My site is BrainBell.com';
 echo substr($str, -13, -4);
 //BrainBell

Format phone number with substr()

This example shows how to format a phone number. To start, the first statement stores the phone number as a string that contains numbers with no formatting characters. Then, the next three statements use the substr function to extract the three parts of the phone number. The final statement joins these three parts together:

<?php
 $phone = 4445556666;

 //Extract three characters, from first character at position 0
 $first = substr($phone,0,3);

 //Extract three characters from fourth character at position 3
 $second = substr($phone,3,3);

 //Extract all characters from seventh character to the end
 $last = substr($phone,6);

echo $first.'-'.$second.'-'.$last;
// Prints: 444-555-6666

mb_substr()

The substr() function will not work on multibyte strings. You must use the multibyte equivalent mb_substr() function instead, as shown in the example:

<?php
 $str = 'Мој сајт је БраинБелл.цом';
 echo substr($str, 12); //not works
 //�т је БраинБелл.цом
 
 echo "\n<br>\n";
 
 echo mb_substr($str, 12); //works
 //БраинБелл.цом

Manipulating substrings: