Forum Moderators: coopster

Message Too Old, No Replies

Counting preg_replace

         

grandpa

5:45 am on Sep 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I see where PHP ver 5.1.0 has added a count parameter to the preg_replace function. Boo hoo, I'm using an older version.

Is there a way to count or to know when a preg_replace actually occurs?

coopster

2:20 pm on Sep 16, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



preg_replace() returns an array if the subject parameter is an array, or a string otherwise. If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Strings would be easy. Compare the original to the new string after the function to see if they are the same. Arrays would follow the same logic, just more code.

grandpa

2:46 pm on Sep 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Strings should be easy. I guess I really should start over and re-write that bit of code. The problem is with the string I'm checking. At one place it might have a valid + sign (or other character), but in another place I want to replace that with a blank space, ie the symbol is not valid.

If I upgrade my PHP then $count would be a simple solution. That could be easier than re-thinking the logic. I'll have another look after a good days sleep :) Thanks.

coopster

10:09 pm on Sep 16, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



What I meant was something like this:
$oldstring = 'Once upon a time ...'; 
$newstring = preg_replace('/Once/', 'Twice', $oldstring);
if ($oldstring <> $newstring) {
print "hey, the string changed to: $newstring";
}

Unless I misunderstood your question ...

grandpa

4:05 am on Sep 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



No, you didn't misunderstand the question :) The strings I'm working with are from raw data in log files, and I'm extracting specific bits. There are cases where I might want to replace a character, and other times when I want to leave the character to preserve parts of the original string. What I'll probably do is look over some code in a stats program like AwStats and see what I can glean from that (maybe a good regex), then re-write my code. At a basic level my code works, I'm trying to refine it a bit.