Home > Article > Backend Development > How to query the occurrence position of a string in php
4 methods: 1. Use stripos() to return the position of the first occurrence (not case sensitive), the syntax is "stripos(string, query value)"; 2. Use strpos(), Return the position of the first occurrence (case-sensitive), the syntax is "strpos(string, query value)"; 3. Use strripos() to return the position of the last occurrence, the syntax is "strripos(string, query value)" ;4. Use strrpos(), the syntax is "strrpos(string, query value)".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
Method 1: Use stripos() Function
stripos() function finds the first occurrence of a string within another string (case-insensitive).
Return value: Returns the position of the first occurrence of a string in another string, or FALSE if the string is not found. Note: The string position starts from 0, not from 1.
<?php header('content-type:text/html;charset=utf-8'); $str="Hello world!"; echo "原字符串:".$str."<br>"; $find="world"; echo "指定子串world的出现位置:".stripos($str,$find); ?>
Method 2: Use the strpos() function
strpos() function to find the first string in another string The position of an occurrence (case sensitive).
Return value: Returns the position of the first occurrence of a string in another string, or FALSE if the string is not found.
<?php header('content-type:text/html;charset=utf-8'); $str="I love php, I love php too!"; echo "原字符串:".$str."<br>"; $find1="php"; echo "指定子串php的出现位置:".strpos($str,$find1)."<br>"; $find2="PHP"; echo "指定子串PHP的出现位置:".strpos($str,$find2); ?>
Method 3: Use strripos() function
strripos() function finds the last string in another string The position of one occurrence (case-insensitive).
Return value: Returns the position of the last occurrence of a string in another string, or FALSE if the string is not found.
<?php header('content-type:text/html;charset=utf-8'); $str="I love php, I love php too!"; echo "原字符串:".$str."<br>"; $find1="php"; echo "指定子串php的出现位置:".strripos($str,$find1)."<br>"; $find2="PHP"; echo "指定子串PHP的出现位置:".strripos($str,$find2); ?>
Method 4: Use the strrpos() function
strrpos() function to find the last string in another string The position of an occurrence (case sensitive).
Return value: Returns the position of the last occurrence of a string in another string, or FALSE if the string is not found.
<?php header('content-type:text/html;charset=utf-8'); $str="I love php, I love php too!"; echo "原字符串:".$str."<br>"; $find1="php"; echo "指定子串php的出现位置:".strrpos($str,$find1)."<br>"; $find2="PHP"; echo "指定子串PHP的出现位置:".strrpos($str,$find2); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to query the occurrence position of a string in php. For more information, please follow other related articles on the PHP Chinese website!