PHP preg_replace()

PHP preg_replace() is a perl style regular expression function. It replaces the specific patterns inside a string using regular expression. The regular expression pattern must be put inside / /. preg_replace() function is much slower than other string functions such as str_replace() which do not support regular expressions.

<?PHP
$str="2000-08-12T03:54:54Z";
$str2=preg_replace("/\-/","/",$str);
echo "$str2"; //2000/08/12T03:54:54Z
?>

preg_replace() function can match different patterns using | symbol.

<?PHP
$str="2000-08-12T03:54:54Z";
$str2=preg_replace("/\-|:/"," ",$str);
echo "$str2"; //2000 08 12T03 54 54Z
?>

When matching multiple patterns using | symbol, preg_replace() function replace the 1st occurrence first, followed by the 2nd occurrence and so on.

<?PHP
$str="what time is the best time when there is no time at all";
$str2=preg_replace("/ time | is |when/","",$str);
//" is " is not replaced since the space has been replaced by " time "
echo "$str2"; //whatis the best therenoat all
$str3=preg_replace("/ time | is | when/","",$str);
//" is " and " when" are not replaced since the spaces
// have been replaced by " time "
echo "$str3"; //whatis the bestwhen therenoat all
?>

You may use () to save reserved patterns. \\1 represents the 1st occurrence of replacement, \\2 the 2nd and so on.

<?PHP
$str="2000-08-12T03:54:54Z";
$str2=preg_replace("/\-(\d+)\-(\d+)T/","/\\2/\\1T",$str);
echo "$str2"; //2000/12/08T03:54:54Z
?>



:: PHP Tutorials Home ::
PHP String Functions
 • concatenation • echo
 • ereg • ereg_replace
 • explode • htmlspecialchars
 • preg_match • preg_replace
 • preg_split • print,sprintf
 • regular expr. • str_replace
 • strcmp • strpos
 • strrev • strrpos
 • strtr • substr
 • substr_replace
PHP Array Functions
 • array_diff • array_flip
 • array_intersect • array_key_exists
 • array_keys • array_merge
 • array_pop • array_push
 • array_rand • array_search
 • array_splice • array_unshift
 • array_values • asort & arsort
 • count • in_array
 • ksort, krsort • shuffle
 • sort
PHP Data Types
 • array • associative array
 • date & time • number
 • class, object • regular expression
 • string • variables
PHP Loop & Conditions
 • continue & break • for loop
 • foreach • if else
 • not equal • while
PHP File System Functions
 • copy • delete, unlink
 • dirname • download url
 • file_exists • is_file, filesize
 • mkdir, rmdir • read file
 • scandir • write file
PHP Popular Topics
 • ajax • clone
 • comments • constants
 • cookie • database
 • defined • die
 • form validation • gd, draw images
 • global variables • header url
 • heredoc • mail
 • pass by reference • print
 • regular expr. • sessions
 • threads • xml parse
PHP Math Functions
 • abs • cos
 • exp • floor & ceil
 • fmod • log
 • max & min • pow
 • round • sin
 • sqrt • tan
endmemo.com © 2024  | Terms of Use | Privacy | Home