eregi_replace problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

eregi_replace problem

Post by yaron »

hello all,
I try to use eregi_teplace in order to hilight search words.
here is my command:

Code: Select all

<?php
$hilighted=eregi_replace($sWord,"<SPAN style='background:yellow;'>$sWord</SPAN>",$resArr['field']);

?>
the hilighting is ok but eregi changes my search word ($sWord) to lower or upper case (depends on how the search word was typed).
What I want to do is to be able to find the search word regardless of the case (that is why i use eregi_replace) but to display the search word (hilighted) in the original form (lower or higher case)
any ideas?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

use a subpattern for replacement

Code: Select all

<?php
$subject = 'A preg_replace Test';
$sWord = 'PREG';
$hilighted=preg_replace('!('.$sWord.')!i',"<SPAN style='background:yellow;'>\\1</SPAN>",$subject); 
echo $hilighted;
?>
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post by m3rajk »

volka wrote:use a subpattern for replacement

Code: Select all

<?php
$subject = 'A preg_replace Test';
$sWord = 'PREG';
$hilighted=preg_replace('!('.$sWord.')!i',"<SPAN style='background:yellow;'>\\1</SPAN>",$subject); 
echo $hilighted;
?>
i ronically, "" are allowed to quote a pattern (that or i have a forgiving set up) and you can use "/($sWord)/i" in place of '!('.$sWord.')!i'

(btw: in the case you're importing the string from someplace else, the delimiter is completely irrelevant.)
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

i ronically, "" are allowed to quote a pattern
of course they are, it's a literal like any other.
But if I have to chose between

Code: Select all

$pattern = '!('.$sWord.')!i';
// and 
$pattern = "!($sWord)!i";
I'll take the first one. I really love syntax highlight ;)
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post by m3rajk »

lol. i find the second easier to type and go with that...
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

Post by yaron »

thanks! it's working fine
Post Reply