Home>Article>Backend Development> How to use strpos in php to get the first occurrence of a string
The method of strpos in php to get the position where a string first appears: first create a PHP sample file; then define a string; finally get the string through "strpos($a,"php");" The location where it first appears is sufficient.
#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
strpos() function is used to find the position where a string appears for the first time in another string. If the specified string is found in the string, it returns the position found starting from 0. If If not, the logical value false is returned.
Specific usage of strpos() function in php
strpos(搜索目标字符串,搜索字符串[,搜索字符串中的起始位置])
It determines whether the target string has a string that needs to be searched, and if it exists, returns the position.
Otherwise return false. If options are specified, the starting position can be changed while searching.
Let’s look at a simple example
Search for “php” in “php Chinese website”
The output results are displayed is 0. If the string php is changed to Chinese website, the output result is 3.
In PHP, 0 may be treated as false depending on how it is written, so you need to pay attention.
Must be used in conditional expressions! == or ===.
The above code searches whether the text php is included in "php Chinese website". Since php is included, a character named php should be displayed, but it will not actually be displayed. This is because the text character The string "php" starts from the first part of $a, so the value returned by strpos is "0".
By setting false in the conditional expression! == strpos($a, "php") will do the trick.
This article ends here. For more exciting content, you can pay attention to the relevant tutorial columns of PHP Chinese! ! !
The above is the detailed content of How to use strpos in php to get the first occurrence of a string. For more information, please follow other related articles on the PHP Chinese website!