PHP Regular Expressions
PHP provides robust support for regular expressions through the built-in preg
functions. These functions allow you to perform pattern matching and manipulation on strings using regular expressions. Here are some commonly used preg
functions in PHP:
preg_match
: This function performs a regular expression match on a string. It returns1
if the pattern is found at least once, and0
otherwise.
php
$pattern = '/hello/';
$string = 'Hello, World!';
if (preg_match($pattern, $string)) {
echo "Pattern found";
} else {
echo "Pattern not found";
}
preg_match_all
: Similar topreg_match
, but it finds all occurrences of the pattern in the string. It returns the number of matches found.
php
$pattern = '/\d+/';
$string = 'I have 3 apples and 5 bananas';
if (preg_match_all($pattern, $string, $matches)) {
echo "Matches found: " . count($matches[0]);
} else {
echo "No matches found";
}
preg_replace
: This function searches for a pattern in a string and replaces all occurrences of the pattern with a specified replacement.
php
$pattern = '/apple/';
$replacement = 'orange';
$string = 'I have an apple and a green apple';
$result = preg_replace($pattern, $replacement, $string);
echo $result; // Output: I have an orange and a green orange
preg_split
: This function splits a string into an array of substrings based on a specified pattern.
php
$pattern = '/\s+/';
$string = 'Hello World';
$result = preg_split($pattern, $string);
print_r($result); // Output: Array ( [0] => Hello [1] => World )
These are just a few examples of the commonly used preg
functions in PHP. Regular expressions in PHP support a wide range of pattern matching capabilities, including character classes, quantifiers, anchors, capturing groups, and more. You can refer to the PHP documentation for more detailed information and additional preg
functions: PHP preg Functions