首页 > 解决方案 > 是否有一种简化的方法来检查字符串数组的每个索引?

问题描述

例如我有这个字符串

$string = "HelloWorld";

我想检查前四个字母是否等于“地狱”

if($string[0]=="H"&&$string[1]=="e"&&$string[2]=="l"&&$string[3]=="l");

有没有更好或简化的检查方法?也许 $string[0-4] 或类似的东西

标签: php

解决方案


如果您只想获取字符串的前 N ​​个字符,可以使用substr

 i.e:
 $string = "HelloWorld";
 $rest   = substr($string , 0, 4);  // returns "Hell"

或者,如果您想检查字符串中是否存在单词,您也可以使用strpos

i.e
$string = "HelloWorld";
$pos = strpos($string , 'Hell'); //will return false if word is not found in string

推荐阅读