Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

preg_replace()

Replace matches with text that can refer to numbered capture groups.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null

Replace matches with text that can refer to numbered capture groups. Braces around a capture number separate it from following digits. The limit applies per pattern per subject. The count argument receives the total substitutions. An invalid pattern returns null for a string subject and an empty array for a one-string array subject.

Signature

preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null

Example output

["A0-12 B7",1]
[null,[]]

Examples

<?php
$out=preg_replace("~([A-Z])(\\d+)~",'${1}0-$2',"A12 B7",1,$n);
echo json_encode([$out,$n]);
set_error_handler(fn($level)=>$level===E_WARNING); $a=preg_replace("~[~","","x"); $b=preg_replace("~[~","",["x"]); restore_error_handler(); echo "\n",json_encode([$a,$b]);

Result

["A0-12 B7",1]
[null,[]]

Sources