views:

25

answers:

1

I need to add an Order ID + Unique ID for each word what starts with @.


For example I have a string like this:

Just @do @it and @do @it.

I want to preg_replace #(\@)+([^\s]+)#i to this:

Just <div id="1+Unique ID">@do</div> <div id="2+Unique ID">@it</div> and <div id="3+Unique ID">@do</div> <div id="4+Unique ID">@it</div>.

+2  A: 

You can use the /e flag to preg_replace to run code for each replacement:

$string = 'Just @do @it and @do @it.';
$id = 0;

echo preg_replace('/@\w+/e', '"<div id=\"".++$id."\">\\0</div>"', $string);

Output:

Just <div id="1">@do</div> <div id="2">@it</div> and <div id="3">@do</div> <div id="4">@it</div>.
John Kugelman
Hey! Thanks very much it works!I can't believe you made it! I was searching for weeks for something like this!!! But could you tell me how should I use it with a `variable` so `preg_replace('/@\w+/e', $replace, $string);`
CIRK
Set `$replace` to the exact string above. Make sure to use the same single and double quotes exactly as I wrote it: `$replace = '"<div id=\"".++$id."\">\\0</div>"';`
John Kugelman
Wow thanks for the fast response :D Let me try it
CIRK
Thanks very very much!
CIRK