开发者

Doing a substring operation based on a regex in PHP

开发者 https://www.devze.com 2022-12-12 22:29 出处:网络
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)

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

精彩评论

暂无评论...
验证码 换一张
取 消