I have a large text containing many dates formatted like this:
10 april 2012, monday
I need to transform all of them into this format:
\r\nmonday, 10 april 2012
So, I wrote a regex and it works perfectly OK.
$matches1= preg_replace(
'#(\d{,2} [a-z]+) \d{4}, (sunday|monday|tuesday|wednesday|thursday|friday|saturday)#u',
"\r\n$2$3$4$5$6$7$8, $1",
$txt);
The problem is that I also need to save all the transformed parts of the text matching the replacement pattern – “\r\n$2$3$4$5$6$7$8, $1” (like \r\nmonday, 10 april 2012) – into an array. So that I have something like this:
Array('\r\nmonday, 10 april 2012', '\r\ntuesday, 11 april 2012', '\r\nfriday, 14 april 2012' etc.)
Is that possible?
Replacement pattern (“\r\n$2$3$4$5$6$7$8, $1”) comes from a html form and may vary.
Update
I’ve tried to write a callback function but I couldn’t get the result I needed.
So I’ve come up with the following:
$text = ...;//some text
$search = ...;//search pattern
$replacement = ...;//replacement pattern
preg_match_all('#' . $search. '#u', $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
{
$replacements[] = preg_replace('#' . $search. '#u', $replacement, $match[0]);
}
$newtext = preg_replace('#' . $search. '#u', $replacement, $text);
So $newtext contains the transformed text and $replacenemts contains all the replacements.
Use
preg_replace_callbackinstead (or exemplary in the following code-example additionally) and keep track of all replacements: