regex question: replace things ONCE

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Dear readers,
i need help on a regular expression:
i have to apply 100 different replaces to an article, but i don't want
that a portion of text already replaced is replaced another time by
another text. the php function strtr() does this but for other reasons
i have to use ereg_replace or preg_replace

to make you understand what i need i paste a portion of the strtr()
function documentation:
strtr() will always look for the longest possible match first and will
*NOT* try to replace stuff that it has already worked on.

so if i have the following replaces:

[cat]=> <a href="#cat">cat</a>
[catalitic] => <a href="#catalitic">catalitic</a>

for the following text= "my cat is catalitic"
so the result should be: my <a href="#cat">cat</a> is <a
and not: <a href="#cat">cat</a> is <a href="#<a href="#cat">cat</
a>alitic"><a href="#cat">cat</a>alitic</a>

i can't use strtr() for a reason that's too long to explain

thank you very much! simone

Re: regex question: replace things ONCE

Greetings, Giakko.
In reply to Your message dated Tuesday, May 13, 2008, 16:03:28,

Quoted text here. Click to load it

[cat]=>> <a href="#cat">cat</a>
[catalitic] =>> <a href="#catalitic">catalitic</a>

Quoted text here. Click to load it

There's a simple way to solve Your problem.
Use regexp modifiers to point that You have the whole word to replace, not a
part of word.
One of them are \b - word boundary.
something like


$text = 'my cat is catalitic';

$replace = array(

echo preg_replace($replace, '<a href="#$0">$0</a>', $text);



Re: regex question: replace things ONCE

Giakko wrote:
Quoted text here. Click to load it

Just do it in one pass. preg_replace() don't check again already
processed part of string.

Site Timeline