411 REFERENCE · Wikibooks
PHP Programming/Regular expressions
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Syntax
PHP
?:: ignore the capture group when numeration. Ex: ((?:ignored_substring|other).)
?!: negation. Ex: ((?!excluded_substring).)
$1: first capture group result.
Attention: to search for a dollar, "\$" doesn't work because it's the variables format, so the simple quotes must be used instead of the double quotes: '\$'.
in PHP, the regex patterns must always be surrounded by a delimiter symbol. We generally use the grave accent (`), but we also find / and #.
In addition, we can add some options after these delimiters:
i case insensibility m the "." include carriage returns x ignore spaces o only treat the first match u count the Unicode characters (in multi-byte)
Search
The function ereg(), which allowed to search for a match of a regex in a string, has been replaced by preg_match() since PHP 5.3.
preg_match()
The function preg_matchhttp://php.net/manual/en/function.preg-match.php is the main regex search functionhttp://php.net/manual/en/ref.pcre.php. It returns a Boolean and asks the two mandatory parameters: the regex pattern and the string to scan.
The third parameter represents the variable which stores the results array.
Finally, the fourth accepts an PHP flag allowing to modify the function base behavior.
Minimal example:
<?php
$string = 'PHP regex test for the English Wikibooks.';
if (preg_match('`.*Wikibooks.*`', $string)) {
print('This texts talks about Wikibooks');
} else {
print('This texts doesn\'t talk about Wikibooks');
}
?>
Advanced example:
<?php
$string = 'PHP regex test for the English Wikibooks.';
if (preg_match('`.*Wikibooks.*`', $string), results, $flag) {
var_dump(results);
} else {
print('This texts doesn\'t talk about Wikibooks');
}
?>
Flag examples:http://php.net/manual/en/pcre.constants.php
PREG_OFFSET_CAPTURE: displays the searched substring position in the string.
PREG_GREP_INVERT: displays the inverse in preg_grep().
preg_grep()
This function searches into arrayshttp://php.net/manual/fr/function.preg-grep.php.
preg_match_all()
To get all true results in one array, replace preg_match by preg_match_allhttp://www.expreg.com/pregmatchall.php, and print by print_r.
Example to filter a file content:
$regex = "/\(([^)]*)\)/";
preg_match_all($regex, file_get_contents($filename), $matches);
print_r($matches);
Replacement
preg_replace()
The function preg_replace accepts three parameters: the replaced and replacing string to treat.
<?php
// Replace spaces by underscores
$string = "PHP regex test for the English Wikibooks.";
$sortedString = preg_replace('`( )`', '_', $string);
echo $sortedString;
?>
preg_filter()
Same as preg_replace() but its result only include the replacements.
preg_split()
Decomposes a string.
References