Home > Backend Development > PHP Tutorial > How to check if a string contains a substring in PHP

How to check if a string contains a substring in PHP

不言
Release: 2023-04-05 10:40:02
Original
6254 people have browsed it

This article will introduce you to the method of checking whether a string contains substrings in PHP. For example, a specific line of code can only be run if any input string contains another substring, as we'll see below.

How to check if a string contains a substring in PHP

Let’s look at a specific example

Example 1:

The value of the following code will be true, Because the main string $str contains the substring "this". This will output "true".

<?How to check if a string contains a substring in PHP
$str = &#39;This is Main String&#39;;
 
if (strpos($str, &#39;This&#39;) !== false) {
    echo &#39;true&#39;;
}
?>
Copy after login

Example 2:

The value of the following code will be false because the main string $str does not contain the substring "hello". There will be no output.

<?How to check if a string contains a substring in PHP
$str = &#39;This is Main String&#39;;
$substr = "Hello";
 
if (strpos($str, $substr) !== false) {
    echo &#39;true&#39;;
}
?>
Copy after login

Example 3: String contains substring at the beginning

The following code will check whether the string is concatenated with the substring at the beginning. The value of the following code will be true because the main string $str contains the substring "this" at the beginning.

<?How to check if a string contains a substring in PHP
$str = &#39;This is Main String&#39;;
 
if (strpos($str, &#39;This&#39;) === 0 ) {
    echo &#39;true&#39;;
}
?>
Copy after login

This article has ended here. For more exciting content, you can pay attention to other related column tutorials on the How to check if a string contains a substring in PHP Chinese website! ! !

The above is the detailed content of How to check if a string contains a substring in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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