I'm trying to create a preg_replace pattern to add sequentially increasing numbers in replacements to words. For example, I want to change this:
"Mary had a little lamb"
to this:
"(:word_1:Mary:) (:word_2:had:) (:word_3:a:) (:word_4:little:) (:word_5:lamb:)"
The longest lines would never have more than 16 words. I don't think it would be such a problem, except I can't find anything on sequentially increasing numbers. After much frustration, I thought about just writing an expression that would just make 16 seperate (recursive?) passes through each line, but that seemed kind of insane. Any help would be greatly appreciated.
Thanks!
EDIT:
Basically I just need to prepend each word in a string with "(:word_1:", "(:word_2:", etc., each one increasing incrementally.
Here is your solution. Try this
<?php
$string = "Mary had a little lamb";
$count = 0;
$newstring = preg_replace_callback(
'/\S+/',
function($match) use (&$count) { return (( '(:word_' . $count++ . ':' .$match[0] . ':) ' )); },
$string
);
echo $newstring;
?>
PHP preg_replace_callback function is matching the regex pattern given as the first parameter with the $string given as its third parameter. you can also modify the regex pattern as per your need to match your required value. I also use $count as passing by reference to get the count of matched words.