Pieter
Pieter

Reputation: 32765

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?

Upvotes: 1

Views: 161

Answers (3)

Wookai
Wookai

Reputation: 21733

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';

Upvotes: 2

johannes
johannes

Reputation: 15969

Try this:

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

Upvotes: 0

jab11
jab11

Reputation: 867

so you want a replace...

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

Upvotes: 0

Related Questions