Home >Backend Development >PHP Problem >Whether the php string contains a certain string

Whether the php string contains a certain string

(*-*)浩
(*-*)浩Original
2019-09-07 13:15:096639browse

Whether the php string contains a certain string

When writing a program, you often need to process strings. The most basic thing is to search for strings. To detect whether a string contains a specified string in PHP, you can use the following function

strpos(string,find[,start]);

string: required. Specifies the string to search for.

find: required. Specifies the characters to search for.

start: Optional. Specifies the location from which to start the search.

Example (Recommended learning: PHP programming from entry to proficiency)

<?php
$str = &#39;abcdefghi&#39;;
$find   = &#39;ab&#39;;
$pos = strpos($str, $find);

// 注意:这里使用的是 === 不能使用 ==
// 原因:第一个字符串的位置是从0开始。如果这个字符串位于字符串的开始的地方,就会返回0。
// 如果没有字符串 就返回false。
// 为了区分0和false就必须使用等同操作符 === 或者 !==

//1、使用 === 操作符
if ($pos === false) {
    echo "$find不在$str中";
} else {
    echo "$find在$str中";
}

//或2、使用 !== 操作符
if($pos !== false){
	echo "$find在$str中";
}else{
	echo "$find不在$str中"; 
}
?>

explode

Use explode to judge. The PHP judgment string contains the following code:

function checkstr($str){
 $needle =&#39;a&#39;;//判断是否包含a这个字符
 $tmparray = explode($needle,$str);
 if(count($tmparray)>1){
 return true;
 } else{
 return false;
 }
}

The above is the detailed content of Whether the php string contains a certain string. 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