Bird
Raised Fist0
PHPprogramming~5 mins

Substring extraction in PHP

Choose your learning style10 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.

Practice

(1/5)
1. What does the PHP function substr($text, 2, 3) do?
easy
A. Extracts the first 3 characters of $text
B. Extracts 2 characters from $text starting at index 3
C. Extracts 3 characters from $text starting at index 2
D. Extracts the last 3 characters of $text

Solution

  1. Step 1: Understand substr parameters

    The first parameter is the string, the second is the start index (0-based), and the third is the length of substring.
  2. Step 2: Apply to given function

    Starting at index 2 means the third character, and length 3 means extract 3 characters from there.
  3. Final Answer:

    Extracts 3 characters from $text starting at index 2 -> Option C
  4. Quick Check:

    substr(string, 2, 3) = 3 chars from index 2 [OK]
Hint: Remember start is zero-based, length is how many chars [OK]
Common Mistakes:
  • Confusing start index with length
  • Thinking start counts from 1 instead of 0
  • Assuming length is mandatory
2. Which of the following is the correct syntax to extract a substring from a string $str starting at position 4 with length 5 in PHP?
easy
A. substr($str, 5);
B. substr($str, 4, 5);
C. substr($str, 4);
D. substr($str, 5, 4);

Solution

  1. Step 1: Recall substr syntax

    substr(string, start, length) extracts substring starting at 'start' index with 'length' characters.
  2. Step 2: Match parameters to question

    Start is 4, length is 5, so substr($str, 4, 5) is correct syntax.
  3. Final Answer:

    substr($str, 4, 5); -> Option B
  4. Quick Check:

    substr($str, 4, 5) = correct syntax [OK]
Hint: Syntax is substr(string, start, length) with start zero-based [OK]
Common Mistakes:
  • Swapping start and length values
  • Omitting length when needed
  • Using 1-based start index
3. What will be the output of the following PHP code?
$text = "Hello World!";
echo substr($text, 6, 5);
medium
A. World
B. World!
C. Hello
D. orld!

Solution

  1. Step 1: Identify substring start and length

    Start index is 6 (0-based), length is 5 characters.
  2. Step 2: Extract substring from "Hello World!"

    Index 6 is 'W', next 5 chars are 'World'.
  3. Final Answer:

    World -> Option A
  4. Quick Check:

    substr("Hello World!", 6, 5) = "World" [OK]
Hint: Count characters from zero, then take length chars [OK]
Common Mistakes:
  • Including the exclamation mark mistakenly
  • Starting count from 1 instead of 0
  • Confusing length with end index
4. The following PHP code is intended to extract the substring "cat" from the string "concatenate". What is wrong?
$word = "concatenate";
echo substr($word, 3, 4);
medium
A. The length parameter is too long; it should be 3
B. The start index should be 4 instead of 3
C. The substr function cannot extract "cat" from this string
D. There is no error; the code works correctly

Solution

  1. Step 1: Locate substring "cat" in "concatenate"

    "cat" starts at index 3: c(3), a(4), t(5).
  2. Step 2: Check length parameter

    Length 4 extracts "cate" (4 chars), but "cat" is only 3 chars, so length should be 3.
  3. Final Answer:

    The length parameter is too long; it should be 3 -> Option A
  4. Quick Check:

    substr("concatenate", 3, 3) = "cat" [OK]
Hint: Count exact substring length to avoid extra chars [OK]
Common Mistakes:
  • Using wrong start index
  • Assuming substr auto-trims extra chars
  • Thinking substr can't extract middle parts
5. You have a string $data = "user:john;id:12345;role:admin";. How do you extract the user name "john" using substr and strpos functions in PHP?
hard
A. substr($data, 0, strpos($data, ':'));
B. substr($data, 5, 4);
C. substr($data, strpos($data, ';') + 1, 4);
D. substr($data, strpos($data, ':') + 1, strpos($data, ';') - strpos($data, ':') - 1);

Solution

  1. Step 1: Find start position of username

    Use strpos($data, ':') to find colon after "user", add 1 to start after colon.
  2. Step 2: Find length of username substring

    Find position of first semicolon with strpos($data, ';'), subtract start position and 1 to get length.
  3. Step 3: Use substr with calculated start and length

    substr($data, start, length) extracts "john" correctly.
  4. Final Answer:

    substr($data, strpos($data, ':') + 1, strpos($data, ';') - strpos($data, ':') - 1); -> Option D
  5. Quick Check:

    Use strpos to find delimiters, substr extracts between them [OK]
Hint: Use strpos to find delimiters, substr extracts between them [OK]
Common Mistakes:
  • Hardcoding start and length without dynamic positions
  • Using wrong delimiter positions
  • Extracting wrong substring part
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard