I have a string and want to check if the string provides some word I want to look. For example the string is like below
我有一个字符串,想要检查字符串是否提供了一些我想看的单词。 例如,字符串如下所示
$mypoem="This is a poem from poftut.com to its readers";
There are different way to archive this we will look them below.
有不同的存档方法,下面将介绍它们。
通过使用strpos()函数 (By Using strpos() Function)
strpos is a Php function used to find given word position in a string. If the word exist strpos will return the the start position of the word in the string if not it will return -1 . In this example we will look string poem
in the string variable $mypoem
.
strpos是一个Php函数,用于查找字符串中给定的单词位置。 如果单词存在,则strpos将返回字符串中单词的起始位置,否则将返回-1。 在此示例中,我们将在字符串变量$mypoem
查找字符串poem
。
$mypoem="This is a poem from poftut.com to its readers";
if (strpos($mypoem, 'poem') !== false) {
echo 'true';
}
通过使用preg_match()函数 (By Using preg_match() Function)
preg_match is a regular expression match and gives more details to check. We can look complex words but for now we just look simple word match. In this example we will look string poem
in the string variable $mypoem
.
preg_match是一个正则表达式匹配项,它提供了更多要检查的细节。 我们可以看复杂的单词,但现在我们只看简单的单词匹配。 在此示例中,我们将在字符串变量$mypoem
查找字符串poem
。
$mypoem="This is a poem from poftut.com to its readers";
if (preg_match('/poem/',$mypoem))
echo 'true';
如何检查字符串是否在PHP中包含特定单词? 信息移植 (How To Check If String Contains A Specific Word in PHP? Infografic)
翻译自: https://www.poftut.com/check-string-contains-specific-word-php/