How is the preg_replace function used in PHP?

The preg_replace function is used to perform regular expression replacement operations within a string.

Basic syntax:
preg_replace($pattern, $replacement, $subject);

Explanation of parameters:

  1. $pattern: the regular expression pattern to match
  2. $replacement: a string or array used to replace the matching result
  3. Target string that needs to be matched and replaced.

Return value:
Return the modified string.

They agreed to meet at the park tomorrow.
They decided to meet at the park tomorrow.

$pattern = '/\d+/';
$replacement = '***';
$subject = 'hello 123 world';
$result = preg_replace($pattern, $replacement, $subject);
echo $result; // 输出:hello *** world

In the example above, the regular expression pattern “/\d+/” is used to match consecutive numbers, replaced with “***”, and finally output the replaced string “hello *** world”.

In addition to the basic uses mentioned above, preg_replace also supports some special replacement patterns and qualifiers. For example, using “$n” to reference subgroups in the matching result, executing code when using the “e” pattern for replacement, etc. For more details, you can refer to the documentation for the preg_replace function on the official PHP website.

bannerAds