tags:

views:

60

answers:

3

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?

+2  A: 

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';
Wookai
You do not want to use ereg() functions! They are not binary safe and will be removed in future versions of PHP but preg_* functions.
johannes
Argh. You're right ! Editing my answer...
Wookai
You should test if there was a match at all. Otherwise you will get an error when accessing `$groups`.
Gumbo
I did not add checks because his Python code did not, but I guess I should try to be complete when I answer...
Wookai
A: 

so you want a replace...

$filteredDate = preg_replace("([0-9]{2})/([0-9]{2})/([0-9]{4})","$3$2$1",$testString);
jab11
This is missing the pattern delimiters around the regexp and for your string "$3$2$1" $1, $2 and $3 would be interpreted as variables (with an illegal name) before being passed to the preg_repalce() function, you have to use \3\2\1 as I did in my solution.
johannes
A: 

Try this:

$result = preg_replace('#([0-9]{2})/([0-9]{2})/([0-9]{4})#', '\3\2\1' , $data);
johannes
As far as I can tell this does a replacement operation, but it doesn't throw away the rest of the string. I'll have to go with Wookai's solution.
Pieter