Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

str_ireplace

(PHP 5)

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

Описание

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

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

Если subject - массив, поиск и замена производится в каждом элементе этого массива, и возвращается также массив.

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

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

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

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

Замечание: Начиная с PHP 5.0.0 количество произведенных замен может быть получено в необязательном аргументе count, который передается по ссылке. В версиях до PHP 5.0.0 этот аргумент недоступен.

См. также описание функций str_replace(), ereg_replace(), preg_replace() и strtr().



str_pad> <sscanf
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
str_ireplace
n00b at battleofthebits dot org
20-Jul-2007 11:54
Dreamhost hasn't upgraded to PHP 5.0 -- I came up with my own alternative, trying to make it run as much like str_ireplace() as possible.  Adjust the switch-a-roo token if you think it may conflict with your needle in teh haystack.

## HOMEBREW str_ireplace() FOR PRE-PHP 5.0
if (!function_exists('str_ireplace')  {
  function str_ireplace($search,$replace,$subject) {
    $token = '^[[term^]';
    $haystack = strtolower($subject);
    $needle = strtolower($search);
    while (($pos=strpos($haystack,$needle))!==FALSE)  {
      $c++;
      $subject = substr_replace($subject,$token,$pos,strlen($search));
      $haystack = substr_replace($haystack,$token,$pos,strlen($search));
    }
    while (($pos=strpos($subject,$token))!==FALSE)  {
      $subject = substr_replace($subject,$replace,$pos,strlen($token));
    }
    return $subject;
  }
}
lev at taintedthoughts dot com
12-Jun-2007 08:03
There appears to be a "bug" with this function in at least version 5.2.1.

If you attempt to use the function while replacing special characters, such as new lines, it will cause your entire scripts to fail. It resulted in my browser (Firefox 2) trying to download the file instead of parsing it.

Here is example code which will cause problems:

<?php

$sometext
= "this is some text\n";
$sometext .= "that has a new line in it";

echo
break_lines($sometext);

function
break_lines ($text)
 {
 return
str_ireplace("\n", "<br/>", $text);
 }

?>

However, if you simply get rid of the "i" and use the normal str_replace, the page will load just fine.

I have also tried the same code on 5.2.3 and this version does NOT have the same problem, so it does appear to be an issue that was resolved with the newest builds of php.

I don't think it was a result of my personal environment, but I am running Debian-Sarge, Apache 2 and PHP 5.2.1/5.2.3.
hans111 at yahoo dot com
30-Jan-2007 04:26
Yet another one str_ireplace ireplacement, this one will take arrays as $search and $replace

<?php
function make_pattern(&$pat, $key) {
  
$pat = '/'.preg_quote($pat, '/').'/i';
}
if(!
function_exists('str_ireplace')){
    function
str_ireplace($search, $replace, $subject){
        if(
is_array($search)){
           
array_walk($search, 'make_pattern');
        }
        else{
           
$search = '/'.preg_quote($search, '/').'/i';
        }
        return
preg_replace($search, $replace, $subject);
    }
}
?>
Ren
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571