Home  >  Article  >  Backend Development  >  Analysis of substr() function in PHP (with detailed code explanation)

Analysis of substr() function in PHP (with detailed code explanation)

autoload
autoloadOriginal
2021-04-20 10:43:553499browse

Analysis of substr() function in PHP (with detailed code explanation)

In the actual combat of PHP, we often need to parse the URL string and intercept the fragments we need, PHP provides us with the substr() function, we can easily obtain the data we need. This article will take you to take a look at PHP ##substr()Function.

First, let’s take a look at the syntax of the

substr() function:

substr ( string $string , int $start  , int $length = ? )

  • $string: the original string that needs to be intercepted


  • $start: The index position where you want to start (the value can be a positive integer, a negative integer, or 0)


  • $length :The length that needs to be filtered (the value can be a positive integer, a negative integer, or 0). If it is empty, it will be intercepted to the end by default


  • Return value: the new string obtained after interception , returns false if there is an error.

Code example:

1. If the parameters are all non-negative integers

<?php
echo substr(&#39;php.cn is all right&#39;, 1);   
echo "<br>";
echo substr(&#39;php.cn is all right&#39;, 1, 3);  
echo "<br>";
echo substr(&#39;php.cn is all right&#39;, 0, 4);
echo "<br>";  
echo substr(&#39;php.cn is all right&#39;, 0, 8);
?>
输出:        hp.cn is all right
        hp.
        php.
        php.cn i

2.If $ start appears as a negative integer

<?php
echo substr("php.cn is all right", -1);  
echo "<br>"; 
echo substr("php.cn is all right", -2);  
echo "<br>"; 
echo substr("php.cn is all right", -3, 1); 
?>
输出:
t
ht
g

3. If $length appears as a negative integer

<?php
echo substr("php.cn is all right", 0,-1);  
echo "<br>"; 
echo substr("php.cn is all right",2, -1);  
echo "<br>"; 
echo substr("php.cn is all right",4, 4); 
echo "<br>"; 
echo substr("php.cn is all right",-3, -1); 
?>
输出:php.cn is all righ
      p.cn is all righ
      cn i
      gh

Recommended: 2021 PHP Summary of interview questions (collection)》《php video tutorial

The above is the detailed content of Analysis of substr() function in PHP (with detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn