Home >Backend Development >PHP Problem >How to replace variable data with preg_replace in php

How to replace variable data with preg_replace in php

WBOY
WBOYOriginal
2022-06-23 17:03:472082browse

In PHP, the "preg_replace" function can perform a regular expression search and replacement to replace variable data. The syntax is "preg_replace (specifies the search pattern, the string or string array used for replacement, The target string or string array to be searched for and replaced, the maximum number of times the string can be replaced, the number of replacement executions)"; if the subject is an array, the returned result is an array, otherwise a string is returned.

How to replace variable data with preg_replace in php

The operating environment of this article: Windows 10 system, PHP version 8.1, Dell G3 computer

How to replace variable data in preg_replace in php

preg_replace function performs a regular expression search and replace.

Syntax

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

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

Parameter description:

  • $pattern: The pattern to be searched, which can be a string or a string array.

  • $replacement: String or array of strings used for replacement.

  • $subject: The target string or string array to be searched and replaced.

  • $limit: Optional, the maximum number of substitutions for each subject string per pattern. The default is -1 (no limit).

  • $count: Optional, the number of times the replacement is performed.

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.

The example is as follows:

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

The execution result is as follows:

How to replace variable data with preg_replace in php

##Recommended learning: "

PHP Video Tutorial

The above is the detailed content of How to replace variable data with preg_replace in php. 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