PHP - Function preg_replace()


Advertisements


Syntax

mixed preg_replace (mixed pattern, mixed replacement, mixed string [, int limit [, int &$count]] );

Definition and Usage

The preg_replace() function operates just like POSIX function ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.

The optional input parameter limit specifies how many matches should take place.

If the optional paramerter $count is passed then this variable will be filled with the number of replacements done.

Return Value

  • After the replacement has occurred, the modified string will be returned.

  • If no matches are found, the string will remain unchanged.

Example

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
$copy_date = "Copyright 1999";
$copy_date = preg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>

This will produce following result.

Copyright 2000

php_regular_expression.htm

Advertisements