Doing a substring operation based on a regex in PHP
In Python, I can do substring operations based on a regex like this.
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)
What's the PHP equivalent to this?
You could simply use the groups to build your 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';
so you want a replace...
$filteredDate = preg_replace("([0-9]{2})/([0-9]{2})/([0-9]{4})","$3$2$1",$testString);
Try this:
$result = preg_replace('#([0-9]{2})/([0-9]{2})/([0-9]{4})#', '\3\2\1' , $data);
精彩评论