PHP preg_replace

 The PHP preg_replace function can be used to perform a regular expression search and replacement. Simply put, you can find a certain part of the string through a regular method and replace it with new content, such as "Today’s breakfast is very It's delicious", you can use the PHP preg_replace function to replace breakfast with dinner, and become "today's dinner is delicious". In this way, preg_replace is similar to preg_match , different from preg_match which can only do string comparison , preg_replace has more The replaced function.


Basic syntax of PHP preg_replace function

preg_replace ($pattern, $replacement, $subject, $limit = -1, $count)


Search the content of $subject and find the part of $pattern, replace it with $replacement, where $subject can be an array or a string, and $limit is a new feature added in PHP 4.0.2. It is an optional item and refers to the largest Replacement times. The default value is -1, which means unlimited times. The last parameter $count is a new function added in PHP 5.1.0 and is also an optional item. If specified, it will be filled as the completed replacement times.

If the $ subject is an Array , preg_replace dealt returns a Array , if $ subject is a string, the string of anti-back process is completed. Assuming that $pattern is not matched by the search, it will directly return $subject. If an error occurs during the processing, preg_replace will return NULL.

PHP preg_replace function example 1. Replace English words
<?php
$subject="Good morning Mr Smith.";
$pattern='morning';
$replacement='night';
echo preg_replace("/($pattern)/i",$replacement,$subject);
?>
The above output: Good night Mr Smith.

We successfully searched out morning through the PHP preg_replace function and replaced it with night.

PHP preg_replace function example 2. Remove spaces
<?php
$subject="Good morning Mr Smith.";
$pattern='/\s/';
$replacement='';
echo preg_replace("/($pattern)/i",$replacement,$subject);
?>
The above output result: GoodnightMrSmith. The

regular expression of'/\s/' of $parttern will find out the spaces in the $subject string, and we give null values ​​for $replacement. After preg_replace processing, the spaces in the string will disappear! Another common reason for handling errors may be quotes in $pattern or $replacement, which can be handled first with addslashes.

Post a Comment

0 Comments