Home  >  Article  >  Backend Development  >  How to verify whether the first character of a string is the specified value in PHP

How to verify whether the first character of a string is the specified value in PHP

青灯夜游
青灯夜游Original
2022-05-25 20:46:392781browse

3 methods: 1. Use the "strpos($str,"character")==0" statement to determine whether the specified value is the first character, and if true is returned, it is. 2. Use the "$str[0]=="character"" statement, if true is returned. 3. Use the "mb_substr($str,0,1)=="value"" statement.

How to verify whether the first character of a string is the specified value in PHP

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php verification string Is the first character a method to specify a value?

Method 1: Use strpos()

strpos() can perform case-sensitive search Returns the position where the specified character first occurs.

If the returned position is 0, it is the first character; otherwise, it is not.

<?php
header("Content-type:text/html;charset=utf-8");
$str = "abAd235"; 
if(strpos($str,"a")==0){
	echo "字符串第一个字符是指定值";
}else{
	echo "字符串第一个字符不是指定值";
}

?>

How to verify whether the first character of a string is the specified value in PHP

Method 2: Use $str[0]=="specified character"Statement

$str[0]You can access the first character of the string, as long as you determine whether the accessed character is the specified character.

<?php
header("Content-type:text/html;charset=utf-8");
$str = "abAd235"; 
if($str[0]=="A"){
	echo "字符串第一个字符是指定值";
}else{
	echo "字符串第一个字符不是指定值";
}

?>

How to verify whether the first character of a string is the specified value in PHP

Method 3: Use mb_substr()

mb_substr() to intercept the string and intercept the specified starting from the specified position number of characters.

You only need to intercept the first character and determine whether it is the specified value.

<?php
header("Content-type:text/html;charset=utf-8");
$str = "abAd235"; 
echo mb_substr($str,0,1)."<br>";
if(mb_substr($str,0,1)=="a"){
	echo "字符串第一个字符是指定值";
}else{
	echo "字符串第一个字符不是指定值";
}
?>

How to verify whether the first character of a string is the specified value in PHP

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to verify whether the first character of a string is the specified value in PHP. 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