What I want to do is use preg replace to replace matches within a string with a varying replacement, and I was wondering if anyone knew if that is possible in php or at least achievable by some means. For example, a string has two matches, then those matches will be replaced with two different variables. What I want are replacements to each be a unique id and I cannot figure out how this could possibly work or if php could even do this. For example if the match is ‘a’ and there is a sentence, ‘put a smile on a person’ then one ‘a’ will be unique id 98aksd00 and the other will be 09alkj08. I am retrieving my comments from a database so the preg replace is happening within
while ($row=mysql_fetch_assoc($query)){
//preg replace
If anyone could provide any insight into this, I would really appreciate it
You can use
preg_replace_callback(), which will trigger a function call with every match:Edit: to answer the question, this code snippet:
The problem here is that you’re using a double quoted string so you need to escape
\. There’s little reason to use double-quoted strings here. It also makes the syntax more confusing so: