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.
Substring extraction in 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).
<?php $text = "Hello World!"; $part = substr($text, 6, 5); echo $part; // Outputs: World ?>
<?php $text = "Hello World!"; $part = substr($text, 6); echo $part; // Outputs: World! ?>
<?php $text = "Hello"; $part = substr($text, 0, 10); echo $part; // Outputs: Hello ?>
<?php $text = "Hello"; $part = substr($text, -3, 2); echo $part; // Outputs: ll ?>
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 // 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"; ?>
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.
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.