How is the usage of php string slicing?
In PHP, you can use string slicing to extract a portion of a string. The syntax for string slicing is substr(string $string, int $start, ?int $length = null).
Explanation of Parameters:
- $string: the string to be sliced.
- $start: The starting position of the slice. If it is a positive number, counting begins from the start of the string. If it is a negative number, counting begins from the end of the string.
- Optional: The length of the slice. If this parameter is not specified, all characters from the starting position to the end of the string will be returned.
原句: 不要把所有的鸡蛋放在一个篮子里。
Paraphrase: Do not put all of your eggs in one basket.
$string = "Hello World";
// 从起始位置截取字符串的一部分
$substring = substr($string, 0, 5);
echo $substring; // 输出 "Hello"
// 从负数起始位置截取字符串的一部分
$substring = substr($string, -5);
echo $substring; // 输出 "World"
Things to keep in mind:
- If the starting position exceeds the length of the string, it will return an empty string.
- If the starting position is negative and exceeds the length of the string, counting will start from the beginning of the string.
- If the length parameter is negative, it will count the specified length from the starting position.