PHP Regex
Regular expressions, also known as regex, is a powerful tool for pattern matching in text. PHP provides built-in support for regex through the PCRE (Perl Compatible Regular Expressions) library.
To use regex in PHP, you can use the preg_* functions, such as preg_match(), preg_replace(), and preg_split(). These functions take a regular expression pattern as the first argument and a string to search or manipulate as the second argument.
Here are some common regex patterns and how to use them in PHP:
- Matching a string: Use the preg_match() function to match a string against a regex pattern. The function returns 1 if the pattern matches, and 0 otherwise.
if (preg_match('/hello/', 'hello world')) {
echo 'Match found!';
} else {
echo 'No match found.';
}
- Matching a number: Use the \d pattern to match any digit.
if (preg_match('/\d+/', '123')) {
echo 'Match found!';
} else {
echo 'No match found.';
}
- Matching a word: Use the \w pattern to match any word character (letters, numbers, and underscores).
if (preg_match('/\w+/', 'hello_world123')) {
echo 'Match found!';
} else {
echo 'No match found.';
}
- Matching a specific character: Use the [] notation to match a specific character. For example, to match either “a” or “b”, use [ab].
if (preg_match('/[ab]/', 'a')) {
echo 'Match found!';
} else {
echo 'No match found.';
}
- Matching optional characters: Use the ? notation to match an optional character. For example, to match “cat” or “cats”, use /cats?/.
if (preg_match('/cats?/', 'cat')) {
echo 'Match found!';
} else {
echo 'No match found.';
}
- Matching multiple options: Use the | notation to match multiple options. For example, to match either “cat” or “dog”, use /cat|dog/.
if (preg_match('/cat|dog/', 'dog')) {
echo 'Match found!';
} else {
echo 'No match found.';
}
- Capturing groups: Use parentheses () to capture parts of the pattern. The captured groups can be retrieved using the preg_match_all() function.
if (preg_match('/(hello) (world)/', 'hello world', $matches)) {
echo 'Match found!';
echo 'Hello ' . $matches[1] . ', ' . $matches[2] . '!';
} else {
echo 'No match found.';
}
These are just a few examples of what you can do with regex in PHP. Regex is a powerful tool that can be used for complex pattern matching, but it can also be quite daunting for beginners. Start with simple patterns and gradually work your way up to more complex ones as you become more familiar with the syntax.