preg_replace problem


#1
<?php // Dirty [#] Wildcard $wildcard = "[#]"; $wildcardRegEx = "[#]"; $message['body'] = "rawr[#]rawr"; while(strpos($message['body'], $wildcard )) { $random = rand(1, 30000); echo $message['body']; $message['body'] = preg_replace($wildcardRegEx,"$random",$message['body'],1,&$count); echo "
marker$count
"; echo $message['body']; } ?>

output:
rawr[#]rawr
marker0


#2

I don’t know much about regex, but I do know that regex patterns should be between ‘delimiters’, so using forward-slash as a delimiter, yours would be ‘/[#]/’ … I think. Not sure if that’s gonna work.

But why are you using regex anyway? It’s pretty much overkill AND a waste of resources, as regex functions in PHP are quite a bit slower than normal string modifiers. Regex should be used for finding patterns, rather than an instance of a character (or sequence of characters). str_replace() would be perfectly suitable for the code posted by you :slight_smile:


#3

http://www.cuneytyilmaz.com/prog/jrx/
If you don’t know how regex works…don’t try to help me. =( is an escape for special characters in regex.

But why are you using regex anyway? It's pretty much overkill AND a waste of resources, as regex functions in PHP are quite a bit slower than normal string modifiers. Regex should be used for finding patterns, rather than an instance of a character (or sequence of characters). str_replace() would be perfectly suitable for the code posted by you :)

In the ‘real’ version of this…I have to use all 5 variables in preg_replace which I can’t do with str_replace. I simply boiled it down as much as possible


#4

‘Thank you, but that’s not what I meant’ could have been an acceptable reply. Perhaps added with ‘maybe my initial post and the problem description wasn’t clear enough’.

preg_replace() does indeed require pattern delimiters. Where did I talk about backslashes as anything other than escape characters? Reading a reply is part of solving the problem.

Then maybe you should have made that clear, don’t you think? I find it rather rude towards me to throw my reply back in my face like that without even taking the time or effort to properly read my post, or assuming that I know all facets of your problem when you don’t state them in your topicstart.

For now, I’ll just refer you to the following pages, which you can read up on to improve your post quality:

Posting Guidelines
How to ask a smart question
Debugging

Besides that, being rude will not help you get your problem solved, not by me nor by any other user of PHPHelp.com.


#5

But you don’t know how regex works. The regex pattern isn’t the problem…=(