How to use strpos in php to get the first occurrence of a string

不言
Release: 2023-04-04 14:34:01
Original
13034 people have browsed it

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.

How to use strpos in php to get the first occurrence of a string

#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(搜索目标字符串,搜索字符串[,搜索字符串中的起始位置])
Copy after login

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”

<?php
  echo strpos("php中文网","php");
?>
Copy after login

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 ===.

<?php
  $a = "php中文网";
  if(strpos($a,"php")){
    echo "php中文网中有这个字符";
  }
  echo strpos($a,"php");
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!