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:

  1. $string: the string to be sliced.
  2. $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.
  3. 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:

  1. If the starting position exceeds the length of the string, it will return an empty string.
  2. If the starting position is negative and exceeds the length of the string, counting will start from the beginning of the string.
  3. If the length parameter is negative, it will count the specified length from the starting position.
bannerAds