In PHP development, string manipulation is a very common task. Sometimes, we need to extract a portion of a string for further processing. PHP offers a very useful function called substr() specifically designed for this purpose.
The substr() function extracts a part of a string. The function prototype is:
<span class="fun">string substr(string $string, int $start [, int $length])</span>
Parameter explanation:
$str = "Hello, World!";
$sub_str = substr($str, 0, 5);
echo $sub_str; // Outputs "Hello"
The above code extracts the first five characters from the string, resulting in "Hello".
$str = "Hello, World!";
$sub_str = substr($str, 7);
echo $sub_str; // Outputs "World!"
Here, extraction starts from the 7th character to the end of the string, outputting "World!".
$str = "Hello, World!";
$sub_str = substr($str, -6, 5);
echo $sub_str; // Outputs "World"
A negative $start means counting from the end of the string. This example extracts 5 characters starting from the 6th last character, resulting in "World".
The substr() function is an essential and practical tool for string manipulation in PHP. By using the $start and $length parameters flexibly, you can easily extract any part of a string. Mastering this function will make string operations more efficient and concise.