PHP 8.5.0 Alpha 1 available for testing

str_ireplace

(PHP 5, PHP 7, PHP 8)

str_ireplaceVersión insensible a mayúsculas y minúsculas de str_replace()

Descripción

str_ireplace(
    array|string $search,
    array|string $replace,
    string|array $subject,
    int &$count = null
): string|array

str_ireplace() devuelve una cadena de caracteres o un array en el que todas las ocurrencias de search en subject (ignorando mayúsculas y minúsculas), han sido reemplazadas por el valor de replace.

Para reemplazar un texto según un patrón en lugar de una cadena fija, utilice preg_replace() con el modificador de patrón i ..

Parámetros

Si los parámetros search y replace son arrays, entonces la función str_ireplace() tomará un valor de cada array y los utilizará para la búsqueda y el reemplazo en subject. Si el parámetro replace tiene menos valores que el parámetro search, entonces una chaîne de caractères vacía será utilizada como valor para el resto de los valores de reemplazo. Si el parámetro search es un array y el parámetro replace es una chaîne de caractères, entonces esta chaîne de caractères de reemplazo será utilizada para cada valor de search. Lo contrario no tiene sentido.

Si el parámetro search o el parámetro replace son arrays, sus elementos son tratados del primero al último.

search

El valor a buscar, conocido también como needle. Un array puede ser utilizado para designar múltiples needles.

replace

El valor de reemplazo utilizado para cada valor encontrado en search. Un array puede ser utilizado para designar múltiples reemplazos.

subject

Una chaîne de caractères o un tableau en el que se realiza la búsqueda, también conocido como haystack.

Si subject es un array, el reemplazo se realiza en cada uno de los elementos del sujeto subject, y el valor devuelto es también un array.

count

Si se proporciona, esta variable contendrá el número de reemplazos realizados.

Valores devueltos

Devuelve una cadena o un array de reemplazo.

Historial de cambios

Versión Descripción
8.2.0 Case folding no longer depends on the locale set with setlocale(). Only ASCII case folding will be done. Non-ASCII bytes will be compared by their byte value.

Ejemplos

Ejemplo #1 Ejemplo con str_ireplace()

<?php
$bodytag
= str_ireplace("%body%", "black", "<body text=%BODY%>");
echo
$bodytag; // <body text=black>
?>

Notas

Nota: Esta función es segura binariamente.

Precaución

Orden de reemplazo

Dado que la función str_ireplace() realiza los reemplazos de izquierda a derecha, puede reemplazar un valor previamente insertado durante un reemplazo múltiple. El ejemplo #2 de la documentación de la función str_replace() sobre cómo tratar esta problemática.

Ver también

  • str_replace() - Reemplaza todas las ocurrencias en una string
  • preg_replace() - Buscar y reemplazar mediante expresión regular estándar
  • strtr() - Reemplaza caracteres en un string

add a note

User Contributed Notes 11 notes

up
7
Tom
1 year ago
Attention! str_ireplace does not destroy multibyte characters. But multibyte characters are not replaced case-insensitively.

<?php
echo str_ireplace('Ä', 'Ae_', 'Ägypten'); // Ae_gypten
echo str_ireplace('ä', 'ae_', 'ägypten'); // ae_gypten
echo str_ireplace('ä', 'ae_', 'Ägypten'); // Ägypten
echo str_ireplace('Ä', 'ae_', 'ägypten'); // ägypten
echo str_ireplace('E', 'e_', 'egypt'); // e_gypt
echo str_ireplace('e', 'e_', 'Egypt'); // e_gypt
echo str_ireplace('ä', 'ae_', mb_strtolower('Ägypten')); // ae_gypten
up
26
sawdust
16 years ago
Here's a different approach to search result keyword highlighting that will match all keyword sub strings in a case insensitive manner and preserve case in the returned text. This solution first grabs all matches within $haystack in a case insensitive manner, and the secondly loops through each of those matched sub strings and applies a case sensitive replace in $haystack. This way each unique (in terms of case) instance of $needle is operated on individually allowing a case sensitive replace to be done in order to preserve the original case of each unique instance of $needle.

<?php
function highlightStr($haystack, $needle, $highlightColorValue) {
// return $haystack if there is no highlight color or strings given, nothing to do.
if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
return
$haystack;
}
preg_match_all("/$needle+/i", $haystack, $matches);
if (
is_array($matches[0]) && count($matches[0]) >= 1) {
foreach (
$matches[0] as $match) {
$haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
}
}
return
$haystack;
}
?>
up
17
daevid at daevid dot com
20 years ago
here's a neat little function I whipped up to do HTML color coding of SQL strings.

<?php
/**
* Output the HTML debugging string in color coded glory for a sql query
* This is very nice for being able to see many SQL queries
* @access public
* @return void. prints HTML color coded string of the input $query.
* @param string $query The SQL query to be executed.
* @author Daevid Vincent [[email protected]]
* @version 1.0
* @date 04/05/05
* @todo highlight SQL functions.
*/
function SQL_DEBUG( $query )
{
if(
$query == '' ) return 0;

global
$SQL_INT;
if( !isset(
$SQL_INT) ) $SQL_INT = 0;

//[dv] this has to come first or you will have goofy results later.
$query = preg_replace("/['\"]([^'\"]*)['\"]/i", "'<FONT COLOR='#FF6600'>$1</FONT>'", $query, -1);

$query = str_ireplace(
array (
'*',
'SELECT ',
'UPDATE ',
'DELETE ',
'INSERT ',
'INTO',
'VALUES',
'FROM',
'LEFT',
'JOIN',
'WHERE',
'LIMIT',
'ORDER BY',
'AND',
'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-)
'DESC',
'ASC',
'ON '
),
array (
"<FONT COLOR='#FF6600'><B>*</B></FONT>",
"<FONT COLOR='#00AA00'><B>SELECT</B> </FONT>",
"<FONT COLOR='#00AA00'><B>UPDATE</B> </FONT>",
"<FONT COLOR='#00AA00'><B>DELETE</B> </FONT>",
"<FONT COLOR='#00AA00'><B>INSERT</B> </FONT>",
"<FONT COLOR='#00AA00'><B>INTO</B></FONT>",
"<FONT COLOR='#00AA00'><B>VALUES</B></FONT>",
"<FONT COLOR='#00AA00'><B>FROM</B></FONT>",
"<FONT COLOR='#00CC00'><B>LEFT</B></FONT>",
"<FONT COLOR='#00CC00'><B>JOIN</B></FONT>",
"<FONT COLOR='#00AA00'><B>WHERE</B></FONT>",
"<FONT COLOR='#AA0000'><B>LIMIT</B></FONT>",
"<FONT COLOR='#00AA00'><B>ORDER BY</B></FONT>",
"<FONT COLOR='#0000AA'><B>AND</B></FONT>",
"<FONT COLOR='#0000AA'><B>OR</B> </FONT>",
"<FONT COLOR='#0000AA'><B>DESC</B></FONT>",
"<FONT COLOR='#0000AA'><B>ASC</B></FONT>",
"<FONT COLOR='#00DD00'><B>ON</B> </FONT>"
),
$query
);

echo
"<FONT COLOR='#0000FF'><B>SQL[".$SQL_INT."]:</B> ".$query."<FONT COLOR='#FF0000'>;</FONT></FONT><BR>\n";

$SQL_INT++;

}
//SQL_DEBUG
?>
up
6
Anteaus
10 years ago
If you follow the instructions given here you will end up with code which works in php5.3 but which bugs-out in php5.4. Reason is that '&$count' (explicit pass by reference) is now an illegal construct.
Nasty, especially it leads to unreliable code which may work on test but not in production. Manual needs corrected!
up
5
stepanic dot matija at gmail dot com
14 years ago
FIX-ed problem with highlighting second 'o' OR 'a', in this string

<?php
function highlight_string ($haystack, $needle, $highlight_class) {
// return $haystack if there is no highlight color or strings given, nothing to do.

$first_encode='XXXXXXXXXXXXXXX'; //ENCODE string

$second_encode='YYYYYYYYYYYYYYY';

preg_match_all("/$needle+/i", $haystack, $matches);
if (
is_array($matches[0]) && count($matches[0]) >= 1) {
foreach (
$matches[0] as $match) {
$haystack = str_replace($match, $first_encode.$match.$second_encode, $haystack);
}
}

$haystack=str_replace(array($first_encode,$second_encode),
array(
'<font class="'.$highlight_class.'" >','</font>'),$haystack);

return
$haystack;
}
?>
up
4
aidan at php dot net
21 years ago
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
up
3
ishutko at gmail dot com
16 years ago
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
up
4
Psudo - thepsudo at gmail dot com
14 years ago
For highlighting without the overhead of regex and without destroying capitalization, try this:

<?php
function highlight($needle, $haystack){
$ind = stripos($haystack, $needle);
$len = strlen($needle);
if(
$ind !== false){
return
substr($haystack, 0, $ind) . "<b>" . substr($haystack, $ind, $len) . "</b>" .
highlight($needle, substr($haystack, $ind + $len));
} else return
$haystack;
}
?>

This example uses HTML bold tags, but you can easily change the highlighting method.
up
-1
Michael dot Bond at mail dot wvu dot edu
16 years ago
This function will highlight search terms (Key Words in Context).

The difference between this one and the ones below is that it will preserve the original case of the search term as well. So, if you search for "american" but in the original string it is "American" it will retain the capital "A" as well as the correct case for the rest of the string.

<?php
function kwic($str1,$str2) {

$kwicLen = strlen($str1);

$kwicArray = array();
$pos = 0;
$count = 0;

while(
$pos !== FALSE) {
$pos = stripos($str2,$str1,$pos);
if(
$pos !== FALSE) {
$kwicArray[$count]['kwic'] = substr($str2,$pos,$kwicLen);
$kwicArray[$count++]['pos'] = $pos;
$pos++;
}
}

for(
$I=count($kwicArray)-1;$I>=0;$I--) {
$kwic = '<span class="kwic">'.$kwicArray[$I]['kwic'].'</span>';
$str2 = substr_replace($str2,$kwic,$kwicArray[$I]['pos'],$kwicLen);
}

return(
$str2);
}
?>
up
-2
hfuecks at nospam dot org
20 years ago
Note that character case is being defined by your server's locale setting, which effects strings containing non-ASCII characters.

See strtolower() - http://www.php.net/strtolower and comments - internally str_ireplace converts $search and $replace to lowercase to find matches.
up
-4
holblin at holblin dot com
14 years ago
Warning with highlighting ...

I used :

<?php
$text
= preg_replace('/('.$q.')/i','<span class=highlighting "">$1</span>' , $text);
?>

Because this line do not allow to highlight uppercase and lowercase correctly (transform uppercase to lowercase for exemple)

<?php
$text
= str_ireplace( $q , '<span class=highlighting "">'.$q.'</span>', $text);
?>

But when $q contain some regex you have some problems ... for exemple :
<?php $q = '('; ?>

So you must use preg_replace to highlight correctly the text and you must create a function for escape bad regex caracters !

I think that a better function can be found but this works I guess :

<?php
function regex_escape( $q )
{
return
preg_replace('/([\[\]\(\)\{\}\-\.\*\?\|\^\$])/', '\$1', $q);
}
?>
To Top