PHP 程序,用于检查子字符串是否存在于字符串中


2022 年 4 月 22 日, Learn eTutorial
1543

如何使用 PHP 检查字符串是否存在于原始字符串中?

在此程序中,我们将检查字符串是否存在于先前提供的字符串中。为此,我们使用内置函数 strpos() ,它用于查找字符串在字符串中的出现,它基本上是区分大小写的。要执行此程序,我们首先必须将一个句子赋值给变量 string,或者我们也可以将其输入到变量中。之后,我们必须接受用于搜索的第二个字符串,并将其赋值给变量 ser。然后我们必须检查条件 'strpos(string, ser)',如果为真,则打印“该字符串存在于原始字符串中”,否则打印“该字符串不存在于原始字符串中”。

语法


strpos(string,find,start)
 

 

算法

步骤 1:将原始字符串赋值给变量 string

步骤 2:从用户那里接受要搜索的字符串,并将其赋值给变量 ser

步骤 3: 检查条件 'strpos(string, ser)',如果为真,则打印“该字符串存在于原始字符串中”,否则打印“该字符串不存在于原始字符串中”

PHP 源代码

                                          <?php
$string = "Hi! all welcome to learnetutorials.com";
echo "The original string is: \n$string \n";
$ser = readline("Enter the search: \n");
if (strpos($string, $ser)) {
    echo "Yes, The string is present in the original string";
} else {
    echo "No, The string is not present in the original string";
}
?>
                                      

输出

The original string is:
Hi! all welcome to learnetutorials.com
Enter the search:  learn
Yes, The string is present in the original string