How to use the substr function in PHP?

The substr function is used to extract a portion of a string, and its syntax is as follows:

Return part of a string.

Explanation of parameters:

  1. $string: the string to be trimmed.
  2. $start: specifies the starting position for the extraction, which can be a negative number indicating counting from the end of the string.
  3. $length: Optional parameter, specifies the length of the substring to be extracted.

Return value:

  1. Return the extracted string, or false if unsuccessful.

Example of usage:

$string = "Hello, World!";
$result = substr($string, 0, 5);
echo $result; // 输出:Hello

$result = substr($string, 7);
echo $result; // 输出:World!

$result = substr($string, -6);
echo $result; // 输出:World!

$result = substr($string, 7, 5);
echo $result; // 输出:World

In the examples above, the substr function extracts a portion of the string based on the specified starting position and length, and displays the result on the screen.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds