PHP » Strings » preg_replace()

Syntax:
mixed preg_replace(mixed pattern, mixed replacement, mixed string [, int n])
pattern
Perl regular expression pattern.
replacement
Perl regular expression replacement.
string
String to make replacements in.
n
Maximum number of replacements to make.

Makes replacements using Perl regular expressions.

preg_replace makes replacements in one or more strings using one or more patterns. The first three parameters can either be strings or arrays with string elements. The optional n parameter can be used to specify a maximum number of replacements that should be made. A new string with the replacements made is returned. If an array argument is used for the string parameter, all the replacements are applied to all the strings, and an array of strings is returned.

Examples

Code:
<?php

$s = "See http://www.somedomain.com/path/document.html or "
   . "http://www.somedomain.com/path/otherdocument.html";

$pattern = "/(\w)\/(\w*)\//";
$replacement = "$1/newroot/$2/";

print preg_replace($pattern, $replacement, $s);

?>
Output:
See http://www.somedomain.com/newroot/path/document.html or http://www.somedomain.com/newroot/path/otherdocument.html
Explanation:

The paths to the documents in all URLs are modified with a new root directory.

See Also: