Page 1 of 1
*_replace are too good!
Posted: Mon Nov 28, 2005 1:57 am
by PnHoPob
Literally... they're doing their job too well for me
Code: Select all
$string = "abcdeiou";
$string = str_replace("a", "Dear(", $string);
//Current string is "Dear(bcdeiou"
$string = str_replace("e", "Sally(", $string);
However, I just want to replace the second e [ Dear(bcd
eiou ], and not the e in Dear.
So, I guess my question is: How do I str or preg replace only stuff that hasn't been replaced yet?
Posted: Mon Nov 28, 2005 2:02 am
by Jenk
Code: Select all
<?php
$string = 'abcdeiou';
$find = array('a', 'e');
$replace = array('Dear(', 'Sally(');
$string = str_replace($find, $replace, $string);
?>

Posted: Mon Nov 28, 2005 2:06 am
by PnHoPob
Well, that's what I've been doing and it seems to me that making an array works the same as doing it separately.
Am I wrong?
Posted: Mon Nov 28, 2005 2:14 am
by Jenk
aha, you are right, my apologies.
A string parser would be the solution then, that uses preg_match (or more likely preg_match_all) with the PREG_OFFSET_CAPTURE flag.. if I get time (which is likely) and I get bored (even more likely) later then I will give writing one a go.
Posted: Mon Nov 28, 2005 2:43 pm
by PnHoPob
cool, thanks!
Let me explain what I'm doing a little better.
I'm trying to convert a file that has both one and two characters long tokens.
First, I replace the two character long tokens so the one longs don't screw up the two longs.
Then, I replace the one character long ones.
However, let's say the character "o" is the "cat" token and the character "horse" is a two long token that has already been replaced.
When "o" is replaced by "cat", the "horse" that has already been replaced becomes "hcatrse".
Posted: Mon Nov 28, 2005 6:07 pm
by Chris Corbyn
Well.... it can be done with regex too...
Code: Select all
$string = "Dear Peter...";
$new = preg_replace('/^(.*?e.*?)e(.*)$/s', '$1a$2', $string); //Dear Pater...
Posted: Mon Nov 28, 2005 7:06 pm
by Jenk
That doesn't achieve what is asked for, that just replaces the 3rd occurance of e in a string.
The problem here is that the replacement value for the 1st search contains a matching string for the 2nd search, so the 1st replacement is broken with the 2nd replacement. (note the e in Dear( gets replaced with Sally( in the example)
I started on a function, but then my employers decided to drop a bomb on me, also known as a notification of redundancy, so I am scrambling for a new job atm
