PHP preg_replace:将所有转换的部分保存到数组中

时间:2012-05-28 13:07:28

标签: php preg-replace

我有一个大文本,其中包含许多格式如下的日期:

 10 april 2012, monday

我需要将所有这些转换为这种格式:

 \r\nmonday, 10 april 2012

所以,我写了一个正则表达式,它完全正常。

 $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);

问题是我还需要保存与替换模式匹配的文本的所有转换部分 - “\ r \ n $ 2 $ 3 $ 4 $ 5 $ 6 $ 7 $ 8,$ 1”(如\ r \ nmonday,2012年4月10日) - 进入一个数组。所以我有这样的事情:

 Array('\r\nmonday, 10 april 2012', '\r\ntuesday, 11 april 2012', '\r\nfriday, 14 april 2012' etc.)

这可能吗?

替换模式(“\ r \ n $ 2 $ 3 $ 4 $ 5 $ 6 $ 7 $ 8,$ 1”)来自html表单,可能会有所不同。

更新

我试过写一个回调函数但是我无法得到我需要的结果。 所以我想出了以下内容:

 $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);

所以$ newtext包含转换后的文本,$ replacenemts包含所有替换。

3 个答案:

答案 0 :(得分:4)

使用preg_replace_callback代替(或在下面的代码示例中示例)并跟踪所有替换:

$search =  '#(\d{,2} [a-z]+) \d{4}, (sunday|monday|tuesday|wednesday|thursday|friday|saturday)#u';
$replace = "\r\n$2$3$4$5$6$7$8, $1";
$captured = array();

preg_replace_callback($search, function($matches) use (&$captured)  {
    $captured[] = $matches;    
}, $txt);

$matches1= preg_replace($search, $replace, $txt);

答案 1 :(得分:1)

使用preg_replace_callback和一个自定义函数,该函数将匹配存储到数组中并返回替换字符串。

答案 2 :(得分:0)

您还可以使用$txtArr = explode(', ', $txt, 1);将字符串拆分到中间的逗号和空格,然后将它们连接在一起,同时使用array_push($matches, $txtArr[1].', '.$txtArr[0]); {{3}将它们推入数组中}。不要忘记定义要添加日期的数组(例如$matches = array();)。

如果它们在一个大的文本字符串中,您可以使用RegEx函数找到它们,并使用它将“已清理”的匹配项放入数组中。