Regex functions in php
A regular expression is a sequence of characters that specifies a search.
In this article, we are going to learn the regex functions used in PHP.
preg_replace — Perform a regular expression search and replace a string we want. In this below example we are going to change the name Benitto to Raj whether the Benitto is spelt correctly or not. ‘i’ flag indicates the case insensitive search. ‘?’ indicates the character before the question mark is optional.
<?php$paragraph = “Listen Benitto, I'm not any of those guys. I am a programmer. Ok, benito?”;$pattern = “/benitt?o/i”;$output = preg_replace($pattern, ”Raj”, $paragraph);var_dump($output);//string(66) "Listen Raj, I'm not any of those guys. I am a programmer. Ok, Raj?"
preg_match — perform a search in a string. if it finds a match it returns 1 otherwise 0.
<?php$paragraph = “Listen Benitto, I'm not any of those guys. I am a programmer. Ok, benito?”;$pattern = “/benitt?o/i”;$output = preg_match($pattern, $paragraph, $matches);var_dump($output);//int(1)var_dump($matches);/** array(1) {
[0]=>
string(7) "Benitto"
} **/
The third parameter we specify is used to store a match. But if you notice it matches the first match and stops. That’s where preg_match_all takes place to find all match.
preg_match_all — perform a global regular expression search. if it finds matches it will return an integer that indicates a number of matches otherwise it returns 0.
<?php$paragraph = “Listen Benitto, I'm not any of those guys. I am a programmer. Ok, benito?”;$pattern = “/benitt?o/i”;$output = preg_match_all($pattern, $paragraph, $matches);var_dump($output);//int(2)var_dump($matches);/** array(1) {
[0]=>
array(2) {
[0]=>
string(7) "Benitto"
[1]=>
string(6) "benito"
}
} **/
preg_split — split a string by regular expression and store a result as an array.
here we split tags by comma, space before and after the comma is optional. ‘*’ indicates 0 or more occurrence of space. ‘\s’ indicates a white space.
<?php$tags = "PHP , Programming, Laravel";$pattern = "/\s*,\s*/i";$output = preg_split($pattern, $tags);var_dump($output);/** array(3) {
[0]=>
string(3) "PHP"
[1]=>
string(11) "Programming"
[2]=>
string(7) "Laravel"
} **/
5.preg_grep
preg_grep — Return array entries that match the pattern. here we only want the sentence that contains the name Benitto whether it is correctly spelt or not.
<?php$comments = [
"Benitto is trustworthy",
"Regex is easy if you understand the characters meanings.",
"Always trust benito"
];$pattern = "/benitt?o/i";$output = preg_grep($pattern,$comments);var_dump($output);/**
array(2) {
[0]=>
string(22) "Benitto is trustworthy"
[2]=>
string(19) "Always trust benito"
}
**/
That’s for this article if you don’t know what the characters mean in the pattern I am going to write a separate article for that. Keep Learning.