Home > Article > Backend Development > How to detect whether a string contains specified characters in php
Two detection methods: 1. Use strpos() to detect the position where the specified character first appears in the string. The syntax is "strpos(string, character, starting position)". If it returns the position representing the position A number means it is included, and if it returns FALSE it means it is not included. 2. Use strrpos() to detect the position of the last occurrence of the specified character in the string. The syntax is "strrpos(string, character, starting position)". If a number representing the position is returned, it means it is included. If it returns FALSE, it means it is not included. .
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php detection string Methods to determine whether a string contains specified characters
Method 1: Use the strpos() function to detect
The strpos() function can find strings in another string The position of the first occurrence in a string (case sensitive).
If the specified character exists, return the position of the first occurrence; if not found, return FALSE.
Note: The string position starts from 0, not from 1.
Example:
<?php header('content-type:text/html;charset=utf-8'); $findme = 'C'; $mystring1 = 'xyz'; $mystring2 = 'ABC'; $pos1 = strpos($mystring1, $findme); $pos2 = strpos($mystring2, $findme); var_dump($pos1); var_dump($pos2); if($pos1){ echo $mystring1." 中指定字符 C<br>"; }else{ echo $mystring1." 中不包含指定字符 C<br>"; } if($pos2){ echo $mystring2." 指定字符 C<br>"; }else{ echo $mystring2." 不包含指定字符 C<br>"; } ?>
Method 2: Use strrpos() function to detect
strrpos() function can Finds the last occurrence of a string within another string (case sensitive).
If the specified character exists, return the position of the last occurrence; if not found, return FALSE.
Example:
<?php header('content-type:text/html;charset=utf-8'); $findme = 'c'; $mystring1 = 'xyzc'; $mystring2 = 'ABC'; $pos1 = strrpos($mystring1, $findme); $pos2 = strrpos($mystring2, $findme); var_dump($pos1); var_dump($pos2); if($pos1){ echo $mystring1." 中指定字符 c<br>"; }else{ echo $mystring1." 中不包含指定字符 c<br>"; } if($pos2){ echo $mystring2." 指定字符 c<br>"; }else{ echo $mystring2." 不包含指定字符 c<br>"; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to detect whether a string contains specified characters in php. For more information, please follow other related articles on the PHP Chinese website!