Home > Backend Development > PHP Tutorial > PHP string exercise 4: Determine whether a string contains a specific word

PHP string exercise 4: Determine whether a string contains a specific word

藏色散人
Release: 2023-04-10 13:12:02
Original
2730 people have browsed it

In "PHP String Exercise 3: 4 Methods for Converting String Sizes", we introduced four common methods for converting the case of strings. In this article, we will continue with strings. The series determines whether a string contains a specific string.

In fact, there is a very simple way to achieve such a judgment. Let’s look at the code directly:

As follows:

<?php
$str1 = &#39;The quick brown fox jumps over the lazy dog.&#39;;
if (strpos($str1,&#39;jumps&#39;) !== false)
{
    echo &#39;特定词出现了&#39;;
}
else
{
    echo &#39;特定词未出现&#39;;
}
Copy after login

In this code, we create a String variable $str1, then we randomly specify the word "jumps" and check to see if this word exists in $str1 through the if...else statement;

Let's take a look at the judgment results first:

PHP string exercise 4: Determine whether a string contains a specific word

As shown in the picture, the result is that "a specific word appears". From the above code, it is indeed true.

So here we mainly use a function strpos and the operator "!==".

The built-in function strpos() in PHP is used to find the first occurrence of a string in another string. Its syntax is "strpos(string,find,start)", where the parameter string specifies the string to be searched, find specifies the string to find, and start is optional and specifies where to start the search; this function returns the position of the first occurrence of the string in another string , returns FALSE if the string is not found.

It should be noted that the strpos() function is case-sensitive.

!== means "absolutely not equal" in comparison operators, !== means "not equal" in array operators .

Finally, I recommend reading "php detects whether a string contains a string". This article introduces other methods of detecting inclusion. Friends who are interested can learn about it~

Recommend the classic course "PHP String Processing (Jade Girl Heart Sutra Edition)", it's free~ come and learn!

The above is the detailed content of PHP string exercise 4: Determine whether a string contains a specific word. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template