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

autoload
Release: 2023-04-09 21:36:02
original
3149 people have browsed it

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 = ? )
Copy after login

  • $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

";
echo substr('php.cn is all right', 1, 3);  
echo "
"; echo substr('php.cn is all right', 0, 4); echo "
"; echo substr('php.cn is all right', 0, 8); ?>
Copy after login
输出:        hp.cn is all right
        hp.
        php.
        php.cn i
Copy after login

2.If $ start appears as a negative integer

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

3. If $length appears as a negative integer

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

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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!