php如何检查字符串中是否包含某个子字符串?
字符串比较可以通过PHP内置函数strpos()轻松完成。
PHP中的STRPOS()函数是检查字符串是否包含特定单词或者子字符串的最简单方法。
strpos()函数在字符串中找到第一次出现子字符串的位置。
如果发现字符串,则返回位置,否则返回false。
使用strpos()函数,我们可以检查字符串是否包含PHP中的特定单词或者字符或者子字符。
以下示例代码片段检查给定字符串中是否存在特定单词。
$string = "Welcome to onitroad, the world of programming."; $word = "onitroad"; if(strpos($string, $word) !== false){ echo "The word '$word' was found in the given string"; }else{ echo "The word '$word' was not found in the given string"; }
以下示例代码检查给定字符串中是否存在特定的子字符串。
<?php $string = "Welcome to onitroad, the world of programming."; $substring = "the world"; if(strpos($string, $substring) !== false){ echo "The substring '$substring' was found in the given string"; }else{ echo "The substring '$substring' was not found in the given string"; }
STRPOS()函数区分大小写,使用stripos()函数是比较时不区分大小写。
日期:2020-06-02 22:15:42 来源:oir作者:oir