Home >Backend Development >PHP Problem >How to find the number of a string in php
Search method: 1. Use strpos(), the syntax "strpos("String value","Search substring") 1"; 2. Use stripos(), the syntax "strpos("String value ","Find substring ") 1". Because strings start counting from 0, the positions obtained by the two functions need to be incremented by 1.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, if you want to find a string, There are two functions to determine the number:
strpos()
stripos()
Both functions can find the first occurrence of a string, and the syntax is similar:
strpos(string,find,start) stripos(string,find,start)
Parameters | Description |
---|---|
string | Required. Specifies the string to be searched for. |
find | Required. Specifies the characters to search for. |
start | Optional. Specifies the location from which to start the search. |
#Return value: Returns the position of the first occurrence of a string in another string, or FALSE if the string is not found.
But the strpos() function is case-sensitive, while the stripos() function is not case-sensitive.
Because strings start counting from 0, the positions obtained by the strpos() and stripos() functions need to be incremented by 1.
Example 1: Use the strpos() function to find the number of the string
<?php header('content-type:text/html;charset=utf-8'); $mystring = 'ABCabc'; $findme1 = 'c'; $pos1 = strpos($mystring, $findme1)+1; echo $findme1." 在第 ".$pos1." 位<br>"; $findme2 = 'C'; $pos2 = strpos($mystring, $findme2)+1; echo $findme2." 在第 ".$pos2." 位<br>"; $findme3 = 'Ca'; $pos3 = strpos($mystring, $findme3)+1; echo $findme3." 在第 ".$pos3." 位<br>"; ?>
Example 2: Use The stripos() function finds the number of a string
<?php header('content-type:text/html;charset=utf-8'); $mystring = 'ABCabc'; $findme1 = 'c'; $pos1 = stripos($mystring, $findme1)+1; echo $findme1." 在第 ".$pos1." 位<br>"; $findme2 = 'C'; $pos2 = stripos($mystring, $findme2)+1; echo $findme2." 在第 ".$pos2." 位<br>"; $findme3 = 'aB'; $pos3 = stripos($mystring, $findme3)+1; echo $findme3." 在第 ".$pos3." 位<br>"; ?>
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to find the number of a string in php. For more information, please follow other related articles on the PHP Chinese website!