PHP Doku:: Ersetzt einen regulären Ausdrück ohne Berücksichtigung von Groß-/Kleinschreibung - function.eregi-replace.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungReguläre Ausdrücke (POSIX-erweitert)POSIX Regex-Funktioneneregi_replace

Ein Service von Reinhard Neidl - Webprogrammierung.

POSIX Regex-Funktionen

<<ereg

eregi>>

eregi_replace

(PHP 4, PHP 5)

eregi_replaceErsetzt einen regulären Ausdrück ohne Berücksichtigung von Groß-/Kleinschreibung

Beschreibung

string eregi_replace ( string $pattern , string $replacement , string $string )

Diese Funktion entspricht ereg_replace() mit dem Unterschied, dass sie übereinstimmende Buchstaben nicht nach Groß- und Kleinschreibung unterscheidet.

Warnung

Diese Funktion ist seit PHP 5.3.0 DEPRECATED (veraltet). Sich auf diese Funktion zu verlassen ist in keiner Weise empfehlenswert.

Parameter-Liste

pattern

Ein POSIX-erweiterter regulärer Ausdruck

replacement

Wenn pattern eingeklammerte Teilzeichenketten enthält, darf replacement Teilzeichenketten der Form \\Ziffer enthalten, die dann durch die Ziffer'ste Teilzeichenkette ersetzt werden. \\0 erzeugt den gesamten Inhalt der durchsuchten Zeichenkette. Bis zu neun Teilzeichenketten dürfen verwendet werden. Klammern dürfen geschachtelt werden und werden in diesem Fall anhand der öffnenden Klammern gezählt.

string

Die zu durchsuchende Zeichenkette

Rückgabewerte

Zurückgegeben wird die geänderte Zeichenkette. Wenn in string keine Übereinstimmungen gefunden werden, wird sie unverändert zurückgegeben.

Beispiele

Beispiel #1 Suchergebnisse hervorheben

<?php
$suchmuster 
'(>[^<]*)('quotemeta($_GET['suche']) .')';
$ersatz '\\1<span class="suche">\\2</span>';
$inhalt eregi_replace($suchmuster$ersatz$inhalt);
?>

Anmerkungen

Hinweis:

Seit PHP 5.3.0 ist die regex-Erweiterung zugunsten der PCRE-Erweiterung als veraltete markiert. Ein Aufruf dieser Funktion wird eine E_DEPRECATED-Notice ausgeben. Sie können sich die Liste der Unterschiede ansehen, wenn Sie Hilfe beim Umstieg auf PCRE benötigen.

Siehe auch

  • ereg() - Sucht Übereinstimmungen mit einem regulären Ausdruck
  • eregi() - Sucht Übereinstimmung mit regulärem Ausdruck ohne Berücksichtigung von Groß-/Kleinschreibung
  • ereg_replace() - Ersetzt einen regulären Ausdruck


32 BenutzerBeiträge:
- Beiträge aktualisieren...
jgriggs777 at yahoo dot com
6.06.2008 16:26
My apologies.  I'm a PHP newbie and the count function didn't work right if you have more than one "keyword".  I searched and spent a long time to get this to work right, so wanted to share it.

This is very easy to use by doing the following.

$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);
   
$the_count = 0;
   
$wordsArray = explode(' ', $words);
        foreach(
$wordsArray as $word) {
         if(
strlen(trim($word)) != 0)
        
        
//exclude these words from being replaced
        
$exclude_list = array("word1", "word2", "word3");
       
// Check if it's excluded
       
if ( in_array( strtolower($word), $exclude_list ) ) {
   
        } else {
           
$text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);
           
$the_count = $count + $the_count;
            }
           
    }
   
//added to show how many keywords were found
   
echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $the_count . "</strong> matches within the " . $the_place. ".</div><br>";
   
    return
$text;
}

//example of how to use
$text_to_highlight = highlight_this($text_to_highlight, $search_text, "Place you searched");

?>
jgriggs777 at yahoo dot com
5.06.2008 21:56
I modified the script from the note below this one so that you could show how many matches were found.  I know this should probably be posted in the str_ireplace() area, so I will post it there afterwards.

$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;
}
?>
a dot dotreppe at gmail dot com
21.05.2008 0:49
Hi everyone.
I saw a lot of highlighting functions, but no one was simple... maybe I missed a part of discussion ?

Anyway, I think this function is the easiest:

<?php
function highlight($text, $words) {
   
$words = trim($words);
   
$wordsArray = explode(' ', $words);
    foreach(
$wordsArray as $word) {
        if(
strlen(trim($word)) != 0)
           
$text = eregi_replace($word, '<span class="highlight">\\0</span>', $text);
    }
    return
$text;
}
?>
dan at dotgospel dot com
23.02.2008 4:30
/*******************************************************
Function highlights the text. You can replace the html tags with whatever you like. $x is the string, $var is the string to be highlighted. We explode the string to highlight more than one word.
*/

function highlight($x,$var) {
    $var = explode(" ",$var);
   
   for($j=0; $j< count($var); $j++){   
        $xtemp = "";
        $i=0;
        while($i<strlen($x)){
            if((($i + strlen($var[$j])) <= strlen($x)) && (strcasecmp($var[$j], substr($x, $i, strlen($var[$j]))) == 0)) {
                    $xtemp .= "<b>" . substr($x, $i , strlen($var[$j])) . "</b>";
                    $i += strlen($var[$j]);
            }
            else {
                $xtemp .= $x{$i};
                $i++;
            }
        }
        $x = $xtemp;
    }
    return $x;
}
mp3spl at o2 dot pl
23.12.2007 13:40
Nice way to highlight that what someone search.

For example is some one search for "Wire Mobile 6"

It will highlight every word separated even if found "Wire Xp and some mobile stuff"

© and ® are importiant, because without special signs, string in second turn will convert also <span class="searchtext">
which will be already in text.

<?

$searchcolor
= explode(' ',$search);
$ilosc = count($searchcolor);
$ilosc2 = "0";
while (
$ilosc2 != $ilosc ) {
$name = eregi_replace ($searchcolor[$ilosc2],'©'.$searchcolor[$ilosc2].'®',$name);
$ilosc2++;
        }
$name = str_replace('©','<span class="searchtext">',$name);
$name = str_replace('®','</span>',$name);

echo
$name;

?>
augusto at fagioli dot biz
21.12.2007 9:50
related to the private at sfiac dot net function,
please note that you  can add a dot in the

$c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);

having it to find email address like user.name@test.com

this is my example
$c=ereg_replace".
   "("[-a-z0-9.!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);
webmaster at hhgroups dot com
28.11.2007 10:24
Your remove links functions are incorrect if there are a php var in the URL, we have to add '?' character inside our pattern, I have three this function working correctly with php vars:

function transformUrl($str){
    $str=utf8_decode(urldecode($str));
    $str=eregi_replace("(^| |>)(www([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"http://\\2\">Look link</a>", $str);
    $str=eregi_replace("(^| |>)(http://www([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"\\2\">Look link</a>", $str);
    $str=eregi_replace("(^| |>)(http://([.]?[a-zA-Z0-9_/-?])[^<]*)", "\\1<a href=\"\\2\">Look link</a>", $str);
    return utf8_encode($str);
}
ash at atomic-network dot co dot uk
31.08.2007 11:46
@bluedragonx at gmail dot com
true but then use of the case insensitive version,
will correct this.

<?php

$_POST
['email'] = str_ireplace("@", "[at]", $_POST['email']);

?>
php[at]drixe[dot]net
24.06.2007 21:49
Melissa,
This one is a better setup for your marvelous code.
It handles Melissa Magic and also Magic Melissa

function underline($subject, $word)
        {
        $mywords = explode(" ",$word);
        for ($j=0;$j<count($mywords);$j++)
            {
            $regex_chars = '\.+?(){}[]^$';
            for ($i=0; $i<strlen($regex_chars); $i++)
                {
                $char = substr($regex_chars, $i, 1);
                $mywords[$j] = str_replace($char, '\\'.$char, $mywords[$j]);
                }
            $mywords[$j] = '(.*)('.$mywords[$j].')(.*)';
            $subject =  eregi_replace($mywords[$j], '\1<span style="background:#ACA;padding:0;margin:0;">\2</span>\3', $subject);
            }
        return $subject;
        }
spiritualmind at gmail dot com
11.06.2007 17:19
eregi_replace seems not to deal with UTF8 chars !
I needed to utf8_decode / encode my string to parse it in eregi_replace :

<?php
  $input
= "string_from_utf8_form" ;
 
$output = utf8_encode(eregi_replace("(pattern)", "replacement", utf8_decode($input)) ;

 echo
$output ;
?>

I think UTF8 is not totally supported by PHP.
Vladimir Luchaninov
22.10.2006 16:38
If you have plain text e-mails and links but need to make them real links

<?
function replaceLinks($text) {
   
// convert support@pogoda.in into
    // <a href="mailto:support@pogoda.in">
    // support@pogoda.in</a>
   
$text = ereg_replace('[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*',
       
'<a href="mailto:\\0">\\0</a>',$text);

   
// convert http://www.pogoda.in/new_york/eng/ into
    // <a href="http://pogoda.in/new_york/eng/">
    // pogoda.in/new_york/eng/</a>
   
$text = ereg_replace('[a-zA-Z]+://(([.]?[a-zA-Z0-9_/-])*)',
       
'<a href="\\0">\\1</a>',$text);

   
// convert www.pogoda.in/new_york/eng/ into
    // <a href="http://www.pogoda.in/new_york/eng/">
    // www.pogoda.in/new_york/eng/</a>
   
$text = ereg_replace('(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)',
       
' <a href="http://\\2">\\2</a>',$text);
   
    return
$text;
}
?>
private at sfiac dot net
8.09.2006 17:44
# I was looking to remove all email address and links from post
# for a non-commercial posting website (like forum or classifieds)

# The function

<?PHP
function verify_email_and_link_in_post($c){
 
# modify email addess and link with this:
 
$l="LINKS ARE PROHIBITED ON THIS WEBSITE";
 
$e="EMAIL ADDRESS ARE PROHIBITER ON THIS WEBSITE";
 
# check for email address
 
$c=ereg_replace".
   "
("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "
$e,$c);
 
# replace all sign @ with the letters at
 
$c=ereg_replace".
   "
("@", " at ",$c);
 
# check for link HTML input
 
$c=eregi_replace".
   "
('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>].*>([^<]*)</a>)',".
   "
$l,$c);
 
# check for anythink like http:// or ftp://
 
$c=ereg_replace".
   "
("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*",".
   "
$l,$c);
 
# check for anyhting starting with www.
 
$c=ereg_replace".
   "
("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)",".
   "
$l,$c);
 
# finaly check for anything like a-z.a-z
 
$c=ereg_replace".
   "
("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+[.]+[-a-z0-9]",".
   "
$l,$c);
 return
$c;
}
?>
# hope this help someone ;-)
carlos at braziland dot com
16.05.2006 2:11
@bluedragonx at gmail dot com: Now you're calling two functions instead of one. I'm trully curious if that would still be faster.

My original post was just to highlight the need to escape characters that could be used to abuse a contact form. Something everyone should do, especially if doing it for a customer.

But bluedragonx, thanks for your input.
melissa at melissagirl dot com
14.04.2006 18:28
Here's a nice case-insensitive highlight function that ignores any regular expression characters and highlights a word and leaves it in whatever case it was before:

<?
function highlight($word, $subject) {
   
$regex_chars = '\.+?(){}[]^$';
    for (
$i=0; $i<strlen($regex_chars); $i++) {
       
$char = substr($regex_chars, $i, 1);
       
$word = str_replace($char, '\\'.$char, $word);
    }
   
$word = '(.*)('.$word.')(.*)';
    return
eregi_replace($word, '\1<span class="highlight">\2</span>\3', $subject);
}
?>

2.11.2005 12:06
@bluedragonx: You're right. And i got the order of the params wrong as well, must've been sleepy when i wrote that note. For what it's worth:

<? $_POST['email'] = str_replace("[at]", "@", strtolower($_POST['email'])); ?>

Not similar to Carlos' code though, since it'll convert all characters to lowercase.
bluedragonx at gmail dot com
17.10.2005 1:42
Actually that wouldn't work because str_replace is case sensitive.  So any instances of [AT] [aT] or [At] would be ignored.
php dot net at nr78 dot net
8.08.2005 14:36
@carlos at braziland dot com: Hate to be a wisecrack, but i believe the following code might be slightly faster with the same result:

<?php

$_POST
['email'] = str_replace("@", "[at]", $_POST['email']);

?>
carlos at braziland dot com
31.07.2005 21:54
So here is my answer to those who are trying to submit headers through my simple contact form:

$any_form_field = eregi_replace("@","[at]",$_POST['just_one_field']); //how can anyone send emails to other email addresses without the @ symbol :)

My suggestion is to do a foreach loop in the $_POST array and remove the @ symbol from all fields (unless you want one of the fields to have the @ symbol, in which case it should be very careful and question if the symbol is necessary).

Not the best solution, but it's simple and it works.
joltmans at amersel dot com
1.03.2005 20:06
PHP's Regex engine differs from several others in its treatment of parsing spaces.

In many Regex languages '\s' denotes a space.
PHP does not recognize '\s', just type a space ' ' instead.

This simple example illustrates the problem:
<?php
    $string
= "A sentence with   spaces";
    if (
eregi("with\s*spaces", $string))
    {
       
// Will never print
       
echo "PHP understood \s";
    }
    else
    {
       
// Will always print
       
echo "PHP doesn't understand \s";
    }
?>

This example does work:
<?php
    $string
= "A sentence with   spaces";
    if (
eregi("with *spaces", $string))
    {
       
// Will print
       
echo "PHP understood ' '";
    }
?>

27.01.2005 17:15
never mind my last post for the eregi_replace not replacing.

I just used str_replace instead and it works fine.  I must have had something wrong with my search string.  POSIX, Perl.. hmm.. yeah probably something there.

Mettedraq / Gene
Ausvald
20.06.2004 1:21
Zach Johnson missed up. ereg* funcs use posix regex, not the rfc one
furiousgreencloud at yahoo dot com
18.06.2004 5:47
To simply convert wild input into a sensable sting, say for a filename I use:

function cleanString($wild) {
    return ereg_replace("[^[:alnum:]+]","",$wild);
}
                                                                               
echo cleanString("@#$&*$@#H~e'{}l{}l<o\{}"); // outputs: Hello
e dot boeters at planet dot nl
4.06.2004 1:46
This is a 'faster' way to highlight search results:

$content = str_replace($query, "<span class=\"highlight\">" . $query . "</span>", $content);
julien at ratatouille dot com dot fr
25.11.2003 3:28
This function replace < and > symbols between <code> and </code> tags by html code for lower than (&lt;) and greather than (&gt;) elements.

function retourne_format_code($texte)
{
    $tablo=split("<code>",$texte);
    $texte="";
    $texte.=$tablo[0];
    foreach($tablo as $cle=>$valeur)
    {
        if(eregi("</code>",$valeur))
        {
            $tablo1=split("</code>",$valeur);
            $tablo1[0]=eregi_replace("<","&lt;",$tablo1[0]);
            $tablo1[0]=eregi_replace(">","&gt;",$tablo1[0]);
            foreach($tablo1 as $cle1=>$valeur1)
            {
                if($cle1==0)
                    $valeur1="<code>".$valeur1."</code>";
                $texte.=$valeur1;
            }
        }       
    }
    return $texte;
}
martin_goldmann at gmx dot net
18.11.2003 21:43
After reading the last message I wrote that de-spamizer:

function despamMailURI($myStrMail='')
{
    ?>javascript:void(location.href='mailto:'+<?=eregi_replace( "^([_\.0-9a-z-]+)@([0-9a-z][0-9a-z-]+)\.([a-z]{2,6})$", "'\\1'+'@'+'\\2'+'.'+'\\3'",$myStrMail)?>)<?
}

Usage example:
<
a href="<?=despamMailURI("user@foo.bar")?>">Mail me</a>
iparanoid at gmx dot de
24.08.2003 6:03
To obtain the an email addresse in the scheme user at host dot use following function

function antispam_mail($mail) {
    return eregi_replace( "^([_\.0-9a-z-]+)@([0-9a-z][0-9a-z-]+)\.([a-z]{2,6})$", '\\1 at \\2 dot \\3',$mail );
};

Combined with a wee JavaScript (document.location='mailto:'+user+'@'+host+'.'+tld) this provides a very powerfull anti-spam mechanism while providing full mailto: link functionality.
chpins-php at romu92 dot freesurf dot fr
3.06.2003 1:15
/*new function for href2text : */

function AHREF2text($string) {
 return eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>].*>([^<]*)</a>)','[\\3] (link: \\2)', $string);
}

// by Ch'Pins
buddy at directpay dot cz
14.05.2003 19:22
i had to solve problem conserning DB2 timestamp format. here is how to parse ANSI timestamp format to DB2 timestamp format:

$mydate = Date("Y-m-d H:i:s");  
 
$var = eregi_replace
("([0-9]{4}-[0-9]{2}-[0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})"
,"\\1-\\2.\\3.\\4",$mydate);

echo "ANSI: $mydate, DB2 format: $var";

happy codding
buddy
eder at xce dot de
4.05.2003 4:23
/*As php at silisoftware dot com's example works only if there is not more than one link in $string, I rewrote his expression to function with strings containing multiple links: */

function AHREF2text($string) {
  return eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','[\\3] (link: \\2)', $string);
}
Rainmaker526 at hotmail.com
10.03.2003 4:02
I have found that some characters cannot be used by eregi_replace (or ereg_replace). When you get the REG_BADRPT error, try backslashing any special chars in your pattern string

ex.
$str = eregi_replace("*", "", $somevar)

gives the REG_BADRPT error. Change it to
$str = eregi_replace("\*", "", $somevar)

to make it work
php at silisoftware dot com
18.02.2003 20:08
Transform HTML links into plain-text "links" with the URL visible

function AHREF2text($string) {
    return eregi_replace('<A .*HREF=("|\')?([^ "\']*)("|\')?.*>([^<]*)</A>', '[\\4] (link: \\2)', $string);
}

$HTMLstring = 'A link to <a href="http://www.php.net">PHP.net</A>';
echo AHREF2text($HTMLstring);
// prints:  A link to [PHP.net] (link: http://www.php.net)
simon_a99 at yahoo dot co dot uk
27.08.2002 21:07
To find a string regardless of case, you might want to use the matched string in the replacement string without changing its case.

For example, you're searching for $search = "letter" and the text being searched is $text = "post lEtTeR".  I want to change the format of the matched string.

Do this:
eregi_replace($search, "<b>\\0</b>", $text);

$text has now been changed to "post <b>lEtTeR</b>".  \\0 is the entire text matched (lEtTer in this case).



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",...)