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

不言
不言Original
2019-02-20 10:11:426255browse

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;;
}
?>

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;;
}
?>

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;;
}
?>

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!

Statement:
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