Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

preg_replace()

Sostituisce le corrispondenze con testo che può riferirsi a gruppi numerati.

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

Sintassi

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

Sostituisce le corrispondenze con testo che può riferirsi a gruppi numerati. Le graffe separano il numero del gruppo dalle cifre successive. Il limite vale per motivo e stringa. count riceve il totale delle sostituzioni. Un errore di compilazione del motivo dà null per una stringa e un array vuoto per un array di una stringa.

Firma

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

Output dell’esempio

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

Esempi

<?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]);

Risultato

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

Fonti