PHP 8.3.4 Released!

preg_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_replaceRealiza una búsqueda y sustitución de una expresión regular

Descripción

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

Busca en subject coincidencias de pattern y las reemplaza con replacement.

Parámetros

pattern

El patrón de búsqueda. Puede ser tanto una cadena como un array de cadenas.

También hay disponibles varios modificadores de PCRE.

replacement

La cadena o array de cadenas a reemplazar. Si este parámetro es una cadena y el parámetro pattern es un array, todos los patrones serán sustituidos por esa cadena. Si ambos parámetros, pattern y replacement, son arrays, cada pattern será reemplazado por el replacement equivalente. Si hay menos elementos en el array replacement que en el array pattern, cualquier pattern extra será reemplazado por una cadena vacía.

replacement puede contener referencias de la forma \\n o $n, siendo preferida la última forma. Cada referencia de este tipo será sustituida por el texto capturado por el n-simo patrón entre paréntesis. n puede ser desde 0 a 99, y \\0 o $0 se refiere al texto coincidido por el patrón completo. Los paréntesis de apertura se cuentan de izquierda a derecha (comenzando por 1) para obtener el número de sub-patrones de captura. Se debe doblar la barra invertida para poder usarla en la sustitución (cadena PHP "\\\\").

Cuando se trabaja con un patrón de sustitución donde una retroreferencia es immediatamente seguida de otro número (p.ej.: colocar un número literal immediatamente después de un patrón coincidido), no puede usar la notación familiar \\1 para sus retroreferencias. \\11, por ejemplo, confundiría a preg_replace() ya que no sabe si quiere que la retroreferencia \\1 esté seguida por un literal 1, o que la retroreferencia \\11 esté seguida de nada. En este caso la solución es usar ${1}1. Esto crea una retroreferencia $1 aislada, dejando el 1 como un literal.

Cuando se usa el modificador obsoleto e, esta función escapa algunos caracteres (a saber, ', ", \ y NULL) en la cadena que sustituye a las retroreferencias. Esto está hecho para asegurarse de que no surjan errores de sintaxis en el uso de retroreferencias con comillas simples o dobles (p.ej. 'strlen(\'$1\')+strlen("$2")'). Asegúrese de que conoce la sintaxis de cadena para saber cómo se asemejarán las cadenas interpretadas.

subject

La cadena o array de cadenas a buscar y sustituir.

Si subject es un array, entonces la búsqueda y sustitución se llevan a cabo para cada entrada de subject, y el valor devuelto también es un array.

limit

Las sustituciones máximas posibles por cada patrón en cada cadena subject. Por defecto es -1 (sin límite).

count

Si se especifica, esta variable será rellenada con el número de sustituciones hechas.

Valores devueltos

preg_replace() devuelve un array si el parámetro subject es un array, o, de lo contrario, una cadena.

Si se encuentran coincidencias, el nuevo subject será devuelto, de lo contrario, subject será devuelto sin cambios o null si se produjo un error.

Errores/Excepciones

Usando el modificador "\e" es un error; y un E_WARNING es emitido en este caso.

Ejemplos

Ejemplo #1 Usar retroreferencias seguidas de literales numéricos

<?php
$cadena
= 'Abril 15, 2003';
$patrón = '/(\w+) (\d+), (\d+)/i';
$sustitución = '${1}1,$3';
echo
preg_replace($patrón, $sustitución, $cadena);
?>

El resultado del ejemplo sería:

Abril1,2003

Ejemplo #2 Emplear arrays indexados con preg_replace()

<?php
$cadena
= 'El veloz murciélago hindú comía feliz cardillo y kiwi.';
$patrones = array();
$patrones[0] = '/veloz/';
$patrones[1] = '/hindú/';
$patrones[2] = '/murciélago/';
$sustituciones = array();
$sustituciones[2] = 'galápago';
$sustituciones[1] = 'africano';
$sustituciones[0] = 'lento';
echo
preg_replace($patrones, $sustituciones, $cadena);
?>

El resultado del ejemplo sería:

El galápago lento africano comía feliz cardillo y kiwi.

Al usar ksort en patrones y sustituciones, podríamos obtener lo que buscábamos.

<?php
ksort
($patrones);
ksort($sustituciones);
echo
preg_replace($patrones, $sustituciones, $cadena);
?>

El resultado del ejemplo sería:

El lento galápago africano comía feliz cardillo y kiwi.

Ejemplo #3 Sustituir varios valores

<?php
$patrones
= array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
'/^\s*{(\w+)}\s*=/');
$sustitución = array ('\4/\3/\1\2', '$\1 =');
echo
preg_replace($patrones, $sustitución, '{fechaInicio} = 1999-5-27');
?>

El resultado del ejemplo sería:

$fechaInicio = 27/5/1999

Ejemplo #4 Quitar los espacios en blanco

Este ejemplo quita los espacios en blanco en exceso de una cadena.

<?php
$cadena
= 'foo o';
$cadena = preg_replace('/\s\s+/', ' ', $cadena);
// Ahora esto será 'foo o'
echo $cadena;
?>

Ejemplo #5 Usar el parámetro count

<?php
$cuenta
= 0;

echo
preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $cuenta);
echo
$cuenta; //3
?>

El resultado del ejemplo sería:

xp***to
3

Notas

Nota:

Cuando se usan arrays con pattern y replacement, las claves se procesan en el orden en que aparecen en el array. Éste no es necesariamente el mismo que el orden de índice numérico. Si usa índices para identificar qué pattern debería ser sustituido por cuál replacement, debería usar ksort() en cada array antes de llamar a preg_replace().

Ver también

add a note

User Contributed Notes 9 notes

up
766
arkani at iol dot pt
15 years ago
Because i search a lot 4 this:

The following should be escaped if you are trying to match that character

\ ^ . $ | ( ) [ ]
* + ? { } ,

Special Character Definitions
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
More Special Character Stuff
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
Even More Special Characters
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
up
4
nik at rolls dot cc
11 years ago
To split Pascal/CamelCase into Title Case (for example, converting descriptive class names for use in human-readable frontends), you can use the below function:

<?php
function expandCamelCase($source) {
return
preg_replace('/(?<!^)([A-Z][a-z]|(?<=[a-z])[^a-z]|(?<=[A-Z])[0-9_])/', ' $1', $source);
}
?>

Before:
ExpandCamelCaseAPIDescriptorPHP5_3_4Version3_21Beta
After:
Expand Camel Case API Descriptor PHP 5_3_4 Version 3_21 Beta
up
2
bublifuk at mailinator dot com
5 years ago
A delimiter can be any ASCII non-alphanumeric, non-backslash, non-whitespace character: !"#$%&'*+,./:;=?@^_`|~- and ({[<>]})
up
1
ismith at nojunk dot motorola dot com
16 years ago
Be aware that when using the "/u" modifier, if your input text contains any bad UTF-8 code sequences, then preg_replace will return an empty string, regardless of whether there were any matches.

This is due to the PCRE library returning an error code if the string contains bad UTF-8.
up
1
php-comments-REMOVE dot ME at dotancohen dot com
16 years ago
Below is a function for converting Hebrew final characters to their
normal equivelants should they appear in the middle of a word.
The /b argument does not treat Hebrew letters as part of a word,
so I had to work around that limitation.

<?php

$text
="עברית מבולגנת";

function
hebrewNotWordEndSwitch ($from, $to, $text) {
$text=
preg_replace('/'.$from.'([א-ת])/u','$2'.$to.'$1',$text);
return
$text;
}

do {
$text_before=$text;
$text=hebrewNotWordEndSwitch("ך","כ",$text);
$text=hebrewNotWordEndSwitch("ם","מ",$text);
$text=hebrewNotWordEndSwitch("ן","נ",$text);
$text=hebrewNotWordEndSwitch("ף","פ",$text);
$text=hebrewNotWordEndSwitch("ץ","צ",$text);
} while (
$text_before!=$text );

print
$text; // עברית מסודרת!

?>

The do-while is necessary for multiple instances of letters, such
as "אנני" which would start off as "אןןי". Note that there's still the
problem of acronyms with gershiim but that's not a difficult one
to solve. The code is in use at http://gibberish.co.il which you can
use to translate wrongly-encoded Hebrew, transliterize, and some
other Hebrew-related functions.

To ensure that there will be no regular characters at the end of a
word, just convert all regular characters to their final forms, then
run this function. Enjoy!
up
0
me at perochak dot com
13 years ago
If you would like to remove a tag along with the text inside it then use the following code.

<?php
preg_replace
('/(<tag>.+?)+(<\/tag>)/i', '', $string);
?>

example
<?php $string='<span class="normalprice">55 PKR</span>'; ?>

<?php
$string
= preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a null or empty string.

<?php
$string
='My String <span class="normalprice">55 PKR</span>';

$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a " My String"
up
-1
sternkinder at gmail dot com
16 years ago
From what I can see, the problem is, that if you go straight and substitute all 'A's wit 'T's you can't tell for sure which 'T's to substitute with 'A's afterwards. This can be for instance solved by simply replacing all 'A's by another character (for instance '_' or whatever you like), then replacing all 'T's by 'A's, and then replacing all '_'s (or whatever character you chose) by 'A's:

<?php
$dna
= "AGTCTGCCCTAG";
echo
str_replace(array("A","G","C","T","_","-"), array("_","-","G","A","T","C"), $dna); //output will be TCAGACGGGATC
?>

Although I don't know how transliteration in perl works (though I remember that is kind of similar to the UNIX command "tr") I would suggest following function for "switching" single chars:

<?php
function switch_chars($subject,$switch_table,$unused_char="_") {
foreach (
$switch_table as $_1 => $_2 ) {
$subject = str_replace($_1,$unused_char,$subject);
$subject = str_replace($_2,$_1,$subject);
$subject = str_replace($unused_char,$_2,$subject);
}
return
$subject;
}

echo
switch_chars("AGTCTGCCCTAG", array("A"=>"T","G"=>"C")); //output will be TCAGACGGGATC
?>
up
-1
mail at johanvandemerwe dot nl
4 years ago
Sample for replacing bracketed short-codes

The used short-codes are purely used for educational purposes for they could be shorter as in 'italic' to 'i' or 'bold' to 'b'.

Sample text
----
This sample shows how to have [italic]italic[/italic], [bold]bold[/bold] and [underline]underlined[/underline] and [strikethrough]striked[/striketrhough] text.

with this function:

<?php
function textDecoration($html)
{
$patterns = [
'/\[(italic)\].*?\[\/\1\] ?/',
'/\[(bold)\].*?\[\/\1\] ?/',
'/\[(underline)\].*?\[\/\1\] ?/'
];

$replacements = [
'<i>$1</i>',
'<strong>$1</strong>',
'<u>$1</u>'
];

return
preg_replace($patterns, $replacements, $html);
}

$html = textDecoration($html);

echo
$html; // or return
?>

results in:
----
This sample shows how to have <i>italic</i>, <b>bold</b> and <u>underlined</u> and [strikethrough]striked[/striketrhough] text.

Notice!
There is no [strikethrough]striked[/striketrhough] fallback in the patterns and replacements array
up
-2
razvan_bc at yahoo dot com
1 year ago
How to replace all comments inside code without remove crln = \r\n or cr \r each line?

<?php
$txt_target
=<<<t1
this;// dsdsds
nope

/*
ok
*/
is;huge
/*text bla*/
/*bla*/

t1;

/*
=======================================================================
expected result:
=======================================================================
this;
nope

is;huge
=======================================================================
visualizing in a hex viewer .. to_check_with_a_hex_viewer.txt ...
t h i s ; LF TAB n o p e CR LF CR LF i s ; h u g e CR LF
74 68 69 73 3b 0a 09 6e 6f 70 65 0d 0a 0d 0a 69 73 3b 68 75 67 65 0d 0a
I used F3 (viewer + options 3: hex) in mythical TOTAL COMMANDER!
=======================================================================
*/

echo '<hr><pre>';
echo
$txt_target;
echo
'</pre>';

// a single line '//' comments
$txt_target = preg_replace('![ \t]*//.*[ \t]*!', '', $txt_target);

// /* comment */
$txt_target = preg_replace('/\/\*([^\/]*)\*\/(\s+)/smi', '', $txt_target);
echo
'<hr><pre>';
echo
$txt_target;
echo
'</pre><hr>';

file_put_contents('to_check_with_a_hex_viewer.txt',$txt_target);

?>
To Top