se_ec
se_ec

Reputation: 19

preg_replace   turns into number

I'm trying to extract only the date part out from "string 2015-08-20".

$original = "string 2015-08-20";

// Trying to remove all but numbers and dashes
$date = preg_replace("#[^0-9-]#iu", '', $original);
// Expecting "2015-08-20"
echo $date;
// But ends up with "1602015-08-20"

Why do I get "160" in front of my string?

Upvotes: 0

Views: 112

Answers (2)

roibeart
roibeart

Reputation: 82

You get 160 probably because in the string that you're handling the non-breaking space is not expressed in the   format but in the   format. Considering that with your regex you replace all the characters that are not numbers or hypens, in the string string 2015-08-20 it keeps the 160, so the result is 1602015-08-20.
This is the exact situation that Phylogenesis describes and solves in his answer.

Here's a more concise solution:

$original = "string 2015-08-20";
$date = preg_replace("#^.*(\d{4}-\d{2}-\d{2})$#", "$1", $original);

It replaces the string with only the content of the group, that is exactly the date part.

Upvotes: 0

Phylogenesis
Phylogenesis

Reputation: 7880

You should really do this the other way round. Search for a datestring, rather than trying to remove everything that isn't a datestring.

This will make the code much more resistant to the unexpected (like a digit being in $original that isn't part of a datestring).

$original = "string 2015-08-20";
preg_match('#\d{4}-\d{2}-\d{2}#', $original, $matches);

# string(10) "2015-08-20"
var_dump($matches[0]);   

Upvotes: 1

Related Questions