In PHP development, string manipulation is a very common task. When you need to extract specific content from a string, PHP offers a very useful function — substr().
The substr() function is used to extract a portion of a string. Its basic syntax is as follows:
<span class="fun">string substr(string $string, int $start [, int $length])</span>
Parameter explanations:
Below are several examples to help understand how to use substr().
$str = "Hello, World!";
$sub_str = substr($str, 0, 5);
echo $sub_str; // Outputs "Hello"
In this example, we extract 5 characters from the beginning of $str and assign it to $sub_str. The output is "Hello".
$str = "Hello, World!";
$sub_str = substr($str, 7);
echo $sub_str; // Outputs "World!"
This example extracts the substring starting from the 7th character to the end of the string, resulting in "World!".
$str = "Hello, World!";
$sub_str = substr($str, -6, 5);
echo $sub_str; // Outputs "World"
Here, a negative start position counts from the end of the string. Starting from the 6th character from the end, we extract 5 characters, resulting in "World".
Note that if $start exceeds the string length, the returned substring will be empty. If $length is negative, it will be treated as zero. Negative parameters allow flexible extraction from the end of the string.
The substr() function is a very practical and commonly used tool in PHP string processing. By flexibly using the $start and $length parameters, you can easily extract any required substring. Mastering this function greatly facilitates daily PHP string operations.