How to find a substring in a string in php
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.
- 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
- 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
- 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.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
