str_ireplace

(PHP 5, PHP 7)

str_ireplaceРегистронезависимый вариант функции str_replace()

Описание

mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Эта функция возвращает строку или массив, в котором все вхождения search в subject заменены на replace (без учета регистра символов). Если не нужны сложные правила поиска/замены, использование этой функции предпочтительнее preg_replace() с модификатором i.

Список параметров

Если search и replace - массивы, то str_ireplace() использует каждое значение из соответствующего массива для поиска и замены в subject. Если в массиве replace меньше элементов, чем в search, в качестве строки замены для оставшихся значений будет использована пустая строка. Если search - массив, а replace - строка, то эта строка замены будет использована для каждого элемента массива search. Обратный случай смысла не имеет.

Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.

search

Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.

replace

Значение замены, будет использовано для замены искомых значений search. Для множества значений можно использовать массив.

subject

Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).

Если subject является массивом, то поиск с заменой будет осуществляться над каждым элементом subject, а результатом функции также будет являться массив.

count

Если передан, то будет установлен в количество произведенных замен.

Возвращаемые значения

Возвращает строку или массив с замененными значениями.

Примеры

Пример #1 Пример использования str_ireplace()

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

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Предостережение

Замечание о порядке замены

Так как str_ireplace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Пример №2 в документации str_replace() поясняет как это работает на практике.

Смотрите также

  • str_replace() - Заменяет все вхождения строки поиска на строку замены
  • preg_replace() - Выполняет поиск и замену по регулярному выражению
  • strtr() - Преобразует заданные символы или заменяет подстроки

Коментарии

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
2004-05-30 13:36:02
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
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 [daevid@LockdownNetworks.com]
 *  @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
?>
2005-04-05 16:14:52
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
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.
2005-07-04 05:07:59
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
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);
}
?>
2008-11-14 08:44:21
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
Автор:
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) < || strlen($haystack) < || 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;
}
?>
2008-12-04 09:28:46
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
2009-03-16 15:49:39
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
Regarding maintaining the case of the find/replace for search-highlighting purposes:

if the performance hit of a regular expression isn't a big problem, there's something like:

<?php
function highlight_matches($find_text$text) {
  return 
preg_replace("/($find_text)/i"'<span class="search_item">$1</span>'$text);
}
?>
2010-09-23 13:06:57
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
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;
}
?>
2010-10-21 23:57:50
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
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);
}
?>
2011-03-09 15:11:14
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
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($haystack0$ind) . "<b>" substr($haystack$ind$len) . "</b>" .
           
highlight($needlesubstr($haystack$ind $len));
    } else return 
$haystack;
}
?>

This example uses HTML bold tags, but you can easily change the highlighting method.
2011-06-30 00:53:07
http://php5.kiev.ua/manual/ru/function.str-ireplace.html
Автор:
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!
2015-01-02 10:41:31
http://php5.kiev.ua/manual/ru/function.str-ireplace.html

    Поддержать сайт на родительском проекте КГБ