Home  >  Article  >  Backend Development  >  How to implement search and replace in php regular

How to implement search and replace in php regular

藏色散人
藏色散人Original
2020-10-15 10:08:472845browse

In PHP, you can use the regular expression "preg_replace ($pattern, $replacement, $subject, $limit, $count)" to achieve search and replacement.

How to implement search and replace in php regular

Recommended: "PHP Video Tutorial"

php regular search and replacement preg_replace

preg_replace — Perform a regular expression search and replacement

Method description:

preg_replace ( $pattern , $replacement , $subject , $limit , $count)

Search for the part of the subject that matches pattern and replace it with replacement.

$limit, $count parameters are optional

limit: The maximum number of substitutions for each pattern on each subject. The default is -1 (unlimited).

count: If specified, will be filled with the number of completed substitutions.

Return value:

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

If a match is found, the replaced subject is returned, otherwise the unchanged subject is returned. If an error occurs, NULL is returned.

Instance 1:

<?php
$PIWIK_API = &#39;filter_offset={offset}&period={period}&date={date}&#39;;
$patterns = array(
    &#39;/{offset}/&#39;,
    &#39;/{period}/&#39;,
    &#39;/{date}/&#39;
);
$replacements = array(
    33,
    &#39;day&#39;,
    &#39;216-11-11&#39;
);
$url = preg_replace($patterns, $replacements, $PIWIK_API);
//结果: $url = "filter_offset=33&period=day&date=216-11-11"

Instance 2:

<?php
$PIWIK_API = array(
    &#39;filter_offset&#39; => &#39;{offset}&#39;,
    &#39;period&#39; => &#39;{period}&#39;,
    &#39;date&#39; => &#39;{date}&#39;
);
$patterns = array(
    &#39;/{offset}/&#39;,
    &#39;/{period}/&#39;,
    &#39;/{date}/&#39;
);
$replacements = array(
    33,
    &#39;day&#39;,
    &#39;216-11-11&#39;
);
$url = preg_replace($patterns, $replacements, $PIWIK_API);
//结果: 
/*
$url = array(3) {
  ["filter_offset"]=>
  string(2) "33"
  ["period"]=>
  string(3) "day"
  ["date"]=>
  string(9) "216-11-11"
}
*/

The above is the detailed content of How to implement search and replace in php regular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn