在PHP中基于正则表达式执行子字符串操作

时间:2009-11-24 16:19:02

标签: php regex

在Python中,我可以根据这样的正则表达式进行子串操作。

rsDate = re.search(r"[0-9]{2}/[0-9]{2}/[0-9]{4}", testString)
filteredDate = rsDate.group()
filteredDate = re.sub(r"([0-9]{2})/([0-9]{2})/([0-9]{4})", r"\3\2\1", filteredDate)

PHP的等价物是什么?

3 个答案:

答案 0 :(得分:2)

您只需使用这些组来构建您的filteredDate:

$groups = array();
if (preg_match("([0-9]{2})/([0-9]{2})/([0-9]{4})", $testString, $groups))
    $filteredDate = sprintf('%s%s%s', $groups[3], $groups[2], $groups[1]);
else
    $filteredDate = 'N/A';

答案 1 :(得分:0)

所以你想要替换......

$filteredDate = preg_replace("([0-9]{2})/([0-9]{2})/([0-9]{4})","$3$2$1",$testString);

答案 2 :(得分:0)

试试这个:

$result = preg_replace('#([0-9]{2})/([0-9]{2})/([0-9]{4})#', '\3\2\1' , $data);