tags:

views:

36

answers:

3

I have 3 separate strings:

$d = 'Created on November 25, 2009';
$v = 'Viewed 17,603 times';
$h = '1,200 hits';

Which needs to be converted to:

$d1 = {unix timestamp of November 25, 2009};

$v1 = "17603"; (commas stripped if it exists)

$h1 = "1200"; (commas stripped if it exists)

What is the most efficient way to do this (possibly with regex)? Any code snippet would be great.

A: 

For the first:

$d_stripped = str_ireplace("Created on ", null, $d);
$created = strtotime($d_stripped);

for the second and third, somebody more proficient with regexes than me will surely provide a good solution.

Pekka
A: 

EDIT: Yes, this isn't too difficult

$d = 'Created on November 25, 2009';
$v = 'Viewed 17,603 times';
$h = '1,200 hits';

$d1 = strtotime( str_replace( 'Created On ', '', $d ) );
$v1 = str_replace( ',', '', preg_replace( '/[a-zA-Z\s]+([0-9,]+)[a-zA-Z ]+/', '$1', $v ) );
$h1 = str_replace( ',', '', preg_replace( '/([0-9,]+)[a-zA-Z ]+/', '$1', $h ) );
Kerry
Your code outputs this: **17603 1200 hits**
Yeti
My bad -- fixed.
Kerry
A: 

Use Kerry's solution with str_replace. Short, maintainable.

You could use a regex to strip the commas but if you can't write it, how are you going to fix it?

OR

You might have no comma (numbers less than 1000), one comma (1,000-999,999), two commas (1,000,000-999,999,999) .. then you could use an expression like:

$v = 'Viewed 17,603 times';
$h = '1,200 hits';
$pattern = '/(\d+)[,]*(\d*)[,]*(\d*)/';
$replacement = '${1}${2}${3}';
echo preg_replace($pattern, $replacement, $v);
echo preg_replace($pattern, $replacement, $h);
Martin Thomas