Home  >  Article  >  Backend Development  >  How to find a substring in a string in php

How to find a substring in a string in php

PHPz
PHPzOriginal
2023-04-11 09:11:321010browse

In PHP, sometimes we need to find a substring in a string and then proceed to the next step based on the result. PHP provides some built-in functions to help us achieve this goal. Here are some commonly used methods.

  1. strpos function

The strpos function is used to find whether a string contains another string and returns the index value of the first matching position. If no matching substring is found, false is returned.

Sample code:

$str = 'Hello, World!';
$substr = 'World';

if (strpos($str, $substr) !== false) {
    echo 'Found';
} else {
    echo 'Not found';
}

The output result is: Found

  1. strstr function

strstr function is used to find whether Contains another string and returns the first matched position and all subsequent characters, or false if no matching substring is found.

Sample code:

$str = 'Hello, World!';
$substr = 'World';

if (strstr($str, $substr) !== false) {
    echo 'Found';
} else {
    echo 'Not found';
}

The output result is: Found

  1. substr_count function

substr_count function is used to calculate a string The number of occurrences of the substring, the return value is an integer type value.

Sample code:

$str = 'Hello, World!';
$substr = 'o';

$count = substr_count($str, $substr);
echo "The substring '$substr' appears in '$str' $count times.";

The output result is: The substring 'o' appears in 'Hello, World!' 2 times.

  1. preg_match function

The preg_match function uses regular expressions to find whether a string contains a matching substring and returns an array of matched ones.

Sample code:

$str = 'Hello, World!';
$pattern = '/W(\w+)/';

if (preg_match($pattern, $str, $matches)) {
    echo 'Found';
    print_r($matches);
} else {
    echo 'Not found';
}

The output result is: Found Array ( [0] => World [1] => orld )

The above are the common ones Of course, there are other more flexible methods that can be used to find substrings under different scenarios and requirements.

The above is the detailed content of How to find a substring in a string 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