String manipulation is a common task in PHP programming, and extracting a part of a string is a frequent requirement. PHP provides the built-in substr() function to accomplish this. In this article, we will explore the usage of the substr() function with detailed code examples to help you understand and apply this feature effectively.
The basic syntax of the substr() function is as follows:
<span class="fun">string substr(string $string, int $start[, int $length])</span>
This function takes three parameters: $string is the original string, $start is the starting position of the substring, and $length is the optional length of the substring. If $length is omitted, the function will extract from the $start position to the end of the string.
Let's start with a simple example to demonstrate how to use the substr() function to extract a part of a string:
<span class="fun">$str = "Hello, PHP!";</span>
<span class="fun">$substring = substr($str, 7);</span>
<span class="fun">echo $substring; // Output: PHP!</span>
In this example, we extract the substring starting from the 7th character of $str, which results in “PHP!”.
We can also use the substr() function to extract a substring of a specific length:
<span class="fun">$str = "Hello, PHP!";</span>
<span class="fun">$substring = substr($str, 7, 3);</span>
<span class="fun">echo $substring; // Output: PHP</span>
In this example, we start extracting from the 7th character and get the next 3 characters, resulting in “PHP”.
By using a negative value for the $start parameter, we can extract the last few characters of a string:
<span class="fun">$str = "Hello, PHP!";</span>
<span class="fun">$substring = substr($str, -4);</span>
<span class="fun">echo $substring; // Output: PHP!</span>
In this case, we set $start to -4, which means we start from the 4th character from the end of the string, extracting the final portion, which results in “PHP!”.
For strings containing Chinese characters, the substr() function may not work correctly because Chinese characters consist of multiple bytes. In such cases, we should use the mb_substr() function, which supports multi-byte characters.
<span class="fun">$str = "你好,PHP!";</span>
<span class="fun">$substring = mb_substr($str, 3, 3, 'UTF-8');</span>
<span class="fun">echo $substring; // Output: PHP</span>
Here, we use mb_substr() to extract 3 characters starting from position 3 in the string $str, and the result is “PHP”.
With these examples, you should have a solid understanding of how to use the substr() function in PHP. We hope these examples help you in performing string manipulation tasks effectively.