0
0
PHPprogramming~10 mins

Substring extraction in PHP - Step-by-Step Execution

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