 |
 |
PHP + ereg_replace
|
 |
|
 |
|
Junior Member
Join Date: May 2003
Status:
Offline
|
|
Hey guys,
I'm doing a simple ereg_replace on a block of text, and I'd like to replace sets of words, not just the characters. example:
If I have the string "He said his head hurts", but I wanted to replace "He" with "That guy", I only want to replace the word "He", and not replace the letters "he" in the word "head". With my current code, the string of text would be translated to: "That guy said his that guyad hurts". See the problem?
Does that make sense? I have posted my code below.
$translate_txt = ereg_replace("He", "That guy", $translate_txt);
Any help would be greatly appreciated.
Jon Marus
|
|
|
| |
|
|
|
 |
|
 |
|
Mac Elite
Join Date: Nov 2003
Location: Minnesota
Status:
Offline
|
|
I haven't tested this, but try:
preg_replace("/\bHe\b/", "That guy", $string);
|
|
|
| |
|
|
|
 |
|
 |
|
Dedicated MacNNer
Join Date: Aug 2002
Status:
Offline
|
|
or you can make sure there are spaces arround it:
ereg_Replace(" He "," That guy ",$string);
(and what about returns... well a more general case would be this 
ereg_replace("([[:space:]])He([[:space"]])","\\1That Guy\\2",$string);
how it works:
[[:space:]] = any white space (tab, space, return)
parentheses allow you to keep something, by refering to it later as \\# where the number is which set of perentheses it is.
--will
|
|
|
| |
|
|
|
 |
|
 |
|
Grizzled Veteran
Join Date: Jun 2001
Location: Melbourne, Australia
Status:
Offline
|
|
Originally posted by clam2000:
or you can make sure there are spaces arround it:
ereg_Replace(" He "," That guy ",$string);
(and what about returns... well a more general case would be this
ereg_replace("([[:space:]])He([[:space"]])","\\1That Guy\\2",$string);
how it works:
[[:space:]] = any white space (tab, space, return)
parentheses allow you to keep something, by refering to it later as \\# where the number is which set of perentheses it is.
--will
I think Turias' code is a bit more robust, as a '\b' word boundary is locale-sensitive, and not all words are seperated by whitespace
e.g.
"He's a funny old goat"
might need to be changed to
"That guy's a funny old goat"
- in this instance, the first word does not have whitespace, but the '\b' assertion will match the start of a line AND the ' character.
A bit picky of me, I know, but while it's subtly different it could make a huge impact on some search strings.
Cheers
|
|
Computer thez nohhh...
|
| |
|
|
|
 |
 |
|
 |
|
|
|
|
|

|
|
 |
Forum Rules
|
 |
 |
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
 |
 |
 |
 |
|
 |
|