Regular expression replace : REGEX

Posted under » PHP on 7 July 2011

Continue from earlier replace article.

Metacharacter

More info.

eg

Matching and groups. eg.

/\\";(.*)content:\\"/gm #regex

\"; }\r\n\r\n. whuteva bp3-i  content:\" #string

g = global and m = multiline. The brackets is to place the wildcard

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.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data