Home >Backend Development >PHP Problem >How to find the number of a string in php

How to find the number of a string in php

青灯夜游
青灯夜游Original
2022-04-22 18:48:552598browse

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.

How to find the number of a string in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$mystring = &#39;ABCabc&#39;;
$findme1 = &#39;c&#39;;
$pos1 = strpos($mystring, $findme1)+1;
echo $findme1." 在第 ".$pos1." 位<br>";

$findme2 = &#39;C&#39;;
$pos2 = strpos($mystring, $findme2)+1;
echo $findme2." 在第 ".$pos2." 位<br>";

$findme3 = &#39;Ca&#39;;
$pos3 = strpos($mystring, $findme3)+1;
echo $findme3." 在第 ".$pos3." 位<br>";
?>

How to find the number of a string in php

Example 2: Use The stripos() function finds the number of a string

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$mystring = &#39;ABCabc&#39;;
$findme1 = &#39;c&#39;;
$pos1 = stripos($mystring, $findme1)+1;
echo $findme1." 在第 ".$pos1." 位<br>";

$findme2 = &#39;C&#39;;
$pos2 = stripos($mystring, $findme2)+1;
echo $findme2." 在第 ".$pos2." 位<br>";


$findme3 = &#39;aB&#39;;
$pos3 = stripos($mystring, $findme3)+1;
echo $findme3." 在第 ".$pos3." 位<br>";

?>

How to find the number of a string in php

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!

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