Bird
Raised Fist0
PHPprogramming~10 mins

Substring extraction in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Substring extraction
Start with full string
↓
Specify start position
↓
Specify length (optional)
↓
Extract substring
↓
Return substring
The program starts with a full string, then chooses where to start and how many characters to take, finally extracting and returning that substring.
Execution Sample
PHP
<?php
$str = "Hello, world!";
$sub = substr($str, 7, 5);
echo $sub;
?>
Extracts 5 characters from position 7 of the string "Hello, world!" and prints it.
Execution Table
StepActionInput StringStart PositionLengthExtracted SubstringOutput
1Define stringHello, world!----
2Call substrHello, world!75--
3Extract substringHello, world!75world-
4Print substringHello, world!75worldworld
5End-----
💡 Extraction done and substring printed; program ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
$str"Hello, world!""Hello, world!""Hello, world!""Hello, world!""Hello, world!"
$subundefinedundefined"world""world""world"
Key Moments - 3 Insights
Why does the substring start at position 7, not 6?
In PHP, string positions start at 0, so position 7 means the 8th character. The execution_table row 2 shows start position 7 used in substr.
What happens if length is omitted?
If length is omitted, substr extracts from start position to the end of the string. This is not shown here but is a common behavior.
Why is the output 'world' and not 'world!'?
Length 5 means exactly 5 characters are taken starting at position 7. The exclamation mark is at position 12, outside the 5 characters. See execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $sub after step 3?
A"world!"
B"Hello"
C"world"
D"orld!"
💡 Hint
Check the 'Extracted Substring' column in row 3 of execution_table.
At which step is the substring printed?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' and 'Output' columns in execution_table.
If the start position was changed to 0 and length to 5, what would $sub be?
A"Hello"
B"world"
C"Hello,"
D"ello,"
💡 Hint
Think about extracting 5 characters from the start of the string "$str".
Concept Snapshot
substr(string, start, length) extracts a substring from 'string'.
Start counts from 0.
Length is optional; if omitted, substring goes to end.
Returns the extracted substring.
Used to get parts of strings easily.
Full Transcript
This example shows how PHP's substr function extracts a part of a string. We start with the string "Hello, world!". We choose position 7 as the start, which is the 8th character because counting starts at zero. We take 5 characters from there. The substring extracted is "world". Then we print it. The program ends after printing. This helps us get any part of a string by specifying where to start and how many characters to take.

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