
Regular expression replace : REGEX
Posted under » PHP on 7 July 2011
Continue from earlier replace article.
Metacharacter
- .* words in between
- ^ Beginning of string
- $ End of string
- . Any character except a newline character
- ? one match
- \s A single whitespace character
- \S A single non-whitespace character
- \d A digit between 0 and 9
- \w An alphabetic or numeric character, or underscore
- [A-Z] An uppercase alphabetic character
- [a-z] A lowercase alphabetic character
- [\r\n]+ or (\r\n|\r|\n) new line
- [0-9] A digit between 0 and 9
- | OR logical operator
- (?= Positive conditional test
- (?! Negative conditional test
- /, @ and # at the beginning and end of the regex pattern
More info.
eg
- ba.*bi The string "foo" in "bafoobi"
- foo The string "foo"
- ^foo "foo" at the start of a string
- foo$ "foo" at the end of a string
- ^foo$ "foo" when it is alone on a string
- [abc] a, b, or c
- [^-\s] or [^\s-] not a whitespace
- [a-z] Any lowercase letter
- [^A-Z] Any character that is not a uppercase letter
- (gif|jpg) Matches either "gif" or "jpeg"
- [a-z]+ One or more lowercase letters
- [0-9\.\-] Аny number, dot, or minus sign
- ^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
- ([wx])([yz]) wy, wz, xy, or xz
- [^A-Za-z0-9] Any symbol (not a number or a letter)
- ([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers
Simple replace
preg_replace("/([Cc]opyright) 200(3|4|5|6)/", "$1 2011", "Copyright 2009");
// Copyright 2011
One match at a time
preg_replace('/(\$.*?\$)/', '-$1-', 'Differentiate $\sqrt[3]{x}$ with respect to ${x}$.');
// Differentiate -$\sqrt[3]{x}$- with respect to -${x}$-.
Note that at times, you have to use single stroke ' instead of "" or regex replace does not work.
Reordering
preg_replace("/(\d+)-(\d+)-(\d+)/", "$2/$3/$1", "2011-01-27");
// 01/27/2011
Array replace
$search = array ( "/(\w{6}\s\(w{2})\s(\w+)/e",
"/(\d{4})-(\d{2})-(\d{2})\s(\d{2}:\d{2}:\d{2})/");
$replace = array ('"$1 ".strtoupper("$2")',
"$3/$2/$1 $4");
$word = "Deleted on | 2011-02-15 05:43:41";
preg_replace($search, $replace, $word);
// Deleted on | 15/02/2011 05:43:41
Remove invisible content
$search = array ('@<head[^>]*?>.*?</head>@siu',
'@<style[^>]*?>.*?</style>@siu',
'@<script[^>]*?.*?</script>@siu');
$replace = array (' ', ' ', ' ');
$word = "some html page";
Not everytime you want to replace the text. Sometimes you just want to find and/or separate them.
This regex tool is very useful.