Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Regular Expression Functions (POSIX Extended) : eregi_replace

eregi_replace

Replace regular expression case insensitive (PHP 4, PHP 5)
string eregi_replace ( string pattern, string replacement, string string )

Example 1895. Highlight search results

<?php
$pattern
= '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

Code Examples / Notes » eregi_replace

ausvald

Zach Johnson missed up. ereg* funcs use posix regex, not the rfc one

php

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)


furiousgreencloud

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


iparanoid

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.


simon_a99

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


e dot boeters

This is a 'faster' way to highlight search results:
$content = str_replace($query, "<span class=\"highlight\">" . $query . "</span>", $content);


julien

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;
}


carlos

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

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-jan-2005 04: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


php

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;
}


vladimir luchaninov

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;
}
?>


rainmaker526

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


buddy

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


melissa

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);
}
?>


spiritualmind

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.


martin_goldmann

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>


bluedragonx

Actually that wouldn't work because str_replace is case sensitive.  So any instances of [AT] [aT] or [At] would be ignored.

shane

A Quick way of removing excess spaces:
<?
$string = "One        Two          Three   Four";
$var = eregi_replace(" +", " ", $string);
echo $var;
?>


php dot net

@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']);
?>


02-nov-2005 11: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.


ash

@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']);
?>


carlos

@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.


chpins-php

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


eder

/*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);
}


private

# 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 ;-)


Change Language


Follow Navioo On Twitter
ereg_replace
ereg
eregi_replace
eregi
split
spliti
sql_regcase
eXTReMe Tracker