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:

<?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:

<?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

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:

  1. Extracting a specific portion of string by position
  2. Searching positions of a substring in a string
  3. How many times a substring occurs in a string
  4. Extract text before or after the match
  5. Replace a portion of string by position
  6. Replace all occurrences of a string with str_replace()
  7. Replace characters or substrings with strtr()
  8. Find a given substring in the string
  9. Manipulating strings: change string case