Easy Tutorial
❮ Func Filesystem Is Link Func String Count Chars ❯

PHP preg_replace() Function

PHP Regular Expressions (PCRE)

The preg_replace function performs a search and replacement of a regular expression.

Syntax

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Searches for parts in subject that match pattern and replaces them with replacement.

Parameter descriptions:

Return Value

If subject is an array, preg_replace() returns an array; otherwise, it returns a string.

If matches are found, the modified subject is returned; otherwise, the unchanged subject is returned. If an error occurs, NULL is returned.

Examples

Replace "google" with "tutorialpro"

<?php
$string = 'google 123, 456';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = 'tutorialpro ${2},$3';
echo preg_replace($pattern, $replacement, $string);
?>

Execution result is as follows:

tutorialpro 123,456

Remove whitespace characters

<?php
$str = 'runo o   b';
$str = preg_replace('/\s+/', '', $str);
// Will change to 'tutorialpro'
echo $str;
?>

Execution result is as follows:

tutorialpro

Use array index-based search and replace

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

Execution result is as follows:

The bear black slow jumped over the lazy dog.

Use the count parameter

<?php
$count = 0;
echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

Execution result is as follows:

xp***to
3

PHP Regular Expressions (PCRE)

❮ Func Filesystem Is Link Func String Count Chars ❯