0
0
PHPprogramming~5 mins

Substring extraction in PHP

Choose your learning style9 modes available
Introduction

Substring extraction helps you get a smaller part of a bigger text. It is like cutting out a piece of a sentence you want to use.

You want to get the first name from a full name string.
You need to extract the area code from a phone number.
You want to get a file extension from a filename.
You want to show only a preview of a long text.
Syntax
PHP
<?php
// Extract substring from a string
$substring = substr($string, $start, $length = null);
?>

$string is the original text.

$start is where to start cutting (0 means start of string).

$length is how many characters to take (optional).

Examples
Extracts 5 characters starting at position 6 (counting from 0).
PHP
<?php
$text = "Hello World!";
$part = substr($text, 6, 5);
echo $part; // Outputs: World
?>
Extracts from position 6 to the end of the string.
PHP
<?php
$text = "Hello World!";
$part = substr($text, 6);
echo $part; // Outputs: World!
?>
If length is longer than string, it returns till end without error.
PHP
<?php
$text = "Hello";
$part = substr($text, 0, 10);
echo $part; // Outputs: Hello
?>
Negative start counts from the end of the string.
PHP
<?php
$text = "Hello";
$part = substr($text, -3, 2);
echo $part; // Outputs: ll
?>
Sample Program

This program shows different ways to get parts of a string using substr. It prints the original text, then extracts a small word, a part from a position to the end, the last 11 characters, and tries to extract more characters than the string length.

PHP
<?php
// Original string
$full_text = "Learning PHP substring extraction.";

// Show original string
echo "Original text: $full_text\n";

// Extract 'PHP' from the string
$extracted_part = substr($full_text, 9, 3);
echo "Extracted part: $extracted_part\n";

// Extract from position 9 to end
$extracted_to_end = substr($full_text, 9);
echo "From position 9 to end: $extracted_to_end\n";

// Extract last 11 characters
$last_eleven = substr($full_text, -11);
echo "Last 11 characters: $last_eleven\n";

// Extract with length longer than string
$long_extract = substr($full_text, 0, 100);
echo "Long extract: $long_extract\n";
?>
OutputSuccess
Important Notes

Time complexity is O(n) where n is the length of the substring extracted.

Space complexity is O(n) for the new substring created.

Common mistake: forgetting that string positions start at 0, so counting starts from zero.

Use substring extraction when you need a specific part of text. For splitting by a character, consider explode() instead.

Summary

Substring extraction gets a smaller piece from a bigger string.

Use substr(string, start, length) to cut out the part you want.

Start counts from zero, and length is optional to go till the end.