PHP Doku:: Groß- und kleinschreibungsunabhängige Version von str_replace - function.str-ireplace.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenstr_ireplace

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<str_getcsv

str_pad>>

str_ireplace

(PHP 5)

str_ireplaceGroß- und kleinschreibungsunabhängige Version von str_replace()

Beschreibung

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

Die Funktion gibt einen String oder ein Array zurück, in dem alle Vorkommen von search innerhalb von subject unabhängig von deren Groß- oder Kleinschreibung gegen den entsprechenden replace-Wert ausgetauscht wurden. Sofern Sie keine speziellen Ersetzungsregeln verwenden, sollten Sie diese Funktion grundsätzlich anstelle von preg_replace() mit i-Modifier verwenden.

Parameter-Liste

search

Hinweis:

Jede Ersetzung aus dem search-Array wird auf dem Ergebnis der jeweils vorhergehenden Ersetzung ausgeführt.

replace

subject

Ist subject ein Array, wird die Suchen-Ersetzen-Funktionalität auf jedes Element von subject angewendet. Die Funktion gibt dann natürlich ein Array zurück.

count

Die Anzahl der gefundenen und ersetzten Textstellen needle wird mittels der an den Parameter count als Referenz übergebenen Variablen zurückgegeben.

Sind search und replace Arrays, dann verwendet str_ireplace() aus beiden Arrays den Wert der aktuellen Zeigerposition, um damit ein Suchen und Ersetzen in subject durchzuführen. Hat replace weniger Werte als search, wird ein leerer String als Wert zum Ersetzen der verbleibenden Elemente verwendet. Ist search ein Array und replace ein String, wird dieser String als Ersetzung für jeden Wert von search verwendet.

Rückgabewerte

Gibt eine Zeichenkette oder ein Array mit ersetzten Werten zurück.

Changelog

Version Beschreibung
5.0.0 Der Parameter count wurde hinzugefügt.

Beispiele

Beispiel #1 str_ireplace()-Beispiel

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

Anmerkungen

Hinweis: Diese Funktion ist binary safe.

Siehe auch

  • str_replace() - Ersetzt alle Vorkommen des Suchstrings durch einen anderen String
  • preg_replace() - Sucht und ersetzt mit regulären Ausdrücken
  • strtr() - Tauscht bestimmte Zeichen aus


12 BenutzerBeiträge:
- Beiträge aktualisieren...
stepanic dot matija at gmail dot com
22.10.2010 5:57
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;
}
?>
triplepoint at gmail dot com
23.09.2010 19:06
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);
}
?>
info at daniel-marschall dot de
22.06.2009 16:15
If you want to keep the original capitalization when replacing some text (e.g. for highlighting the search-string in the the search result), you can use this code I wrote:

<?php

// http://devboard.viathinksoft.de/viewtopic.php?f=34&t=771
// Bugfix-Release #3 (June, 22th 2009)
function ext_str_ireplace($findme, $replacewith, $subject)
{
    
// Replaces $findme in $subject with $replacewith
     // Ignores the case and do keep the original capitalization by using $1 in $replacewith
     // Required: PHP 5

    
$rest = $subject;
    
$result = '';

     while (
stripos($rest, $findme) !== false) {
         
$pos = stripos($rest, $findme);

         
// Remove the wanted string from $rest and append it to $result
         
$result .= substr($rest, 0, $pos);
         
$rest = substr($rest, $pos, strlen($rest)-$pos);

         
// Remove the wanted string from $rest and place it correctly into $result
         
$result .= str_replace('$1', substr($rest, 0, strlen($findme)), $replacewith);
         
$rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme));
     }

    
// After the last match, append the rest
    
$result .= $rest;

     return
$result;
}

?>
ishutko at gmail dot com
16.03.2009 22:49
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
sawdust
4.12.2008 16:28
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;
}
?>
Michael dot Bond at mail dot wvu dot edu
14.11.2008 15:44
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);
}
?>
info at daniel-marschall dot de
2.10.2008 19:32
Example for str_ireplace(). It will print "RePlaCeMe" in red color, but after this, it would be written in lower case because of the string $search.

<?php

$search 
= 'replaceme';
$replace = '<font color="#FF0000">'.$search.'</font>';
$text    = 'Please RePlaCeMe, OK?';

echo
str_ireplace($search, $replace, $text);

?>

Example for ext_str_ireplace(). It will print "RePlaCeMe" in red color, and will not change the capitalization:

<?php

$search 
= 'replaceme';
$replace = '<font color="#FF0000">$1</font>';
$text    = 'Please RePlaCeMe, OK?';

echo
ext_str_ireplace($search, $replace, $text);

?>
Anonymous
5.06.2008 21:58
I modified a script from notes on the eregi_replace() function page.  This is a highlight script that worked good for me.

$text - is the text to search
$words - are the words to highlight (search text)
$the_place - is so that you can tell your users what "area" was searched.

<?php
function highlight_this($text, $words, $the_place) {
   
$words = trim($words);
   
$wordsArray = explode(' ', $words);
    foreach(
$wordsArray as $word) {
        if(
strlen(trim($word)) != 0)
           
$text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
    }
   
//added to show how many keywords were found
   
echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $count . "</strong> matches within the " . $the_place. ".</div><br>";
   
   
//end script modification
   
return $text;
}
?>
mvpetrovich
16.02.2008 0:28
Here are some minor tweaks to-n00b-at-battleofthebits-dot-org's excellent function.
1) The token was set to an ASCII value 1 (which could be changed as was previously noted)
2) The $c++ was not needed
3) The while statement is not necessary for the final replacement
4) Note that this does not allow use of arrays for search and replace terms.  That could be implemented using loops.

<?php
if(!function_exists('str_ireplace')){
  function
str_ireplace($search,$replace,$subject){
   
$token = chr(1);
   
$haystack = strtolower($subject);
   
$needle = strtolower($search);
    while ((
$pos=strpos($haystack,$needle))!==FALSE){
     
$subject = substr_replace($subject,$token,$pos,strlen($search));
     
$haystack = substr_replace($haystack,$token,$pos,strlen($search));
    }
   
$subject = str_replace($token,$replace,$subject);
    return
$subject;
  }
}
?>
hfuecks at nospam dot org
4.07.2005 11:07
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.
daevid at daevid dot com
5.04.2005 22:14
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
?>
aidan at php dot net
30.05.2004 19:36
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



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)