Search code examples
phppreg-match

Want to preg_match numbers and period php


I have this string &OrigPlacedDate=41759.7128& and I want to match the numbers with the period in the correct place. I have tried using

$string = '&OrigPlacedDate=41759.7128&'
$origPlacedDate = '/&OrigPlacedDate=[0-9^\.]*&/';
preg_match($origPlacedDate, $string, $origPlacedDateMatches);
$origPlacedDate = preg_replace('/[^0-9]/', '', $origPlacedDateMatches);
print_r($origPlacedDate);

but I am only getting the numbers.

Array ( [0] => 417597128 ) 

Ultimately I want to get an output of 41759.7128


Solution

  • You were matching numbers, but you weren't including the . in the regular expression. Try this:

    $string = '&OrigPlacedDate=41759.7128&';
    $origPlacedDate = '/&OrigPlacedDate=[0-9^\.]*&/';
    preg_match($origPlacedDate, $string, $origPlacedDateMatches);
    $origPlacedDate = preg_replace('/[^0-9\.]/', '', $origPlacedDateMatches);
    print_r($origPlacedDate);
    

    Output:

    Array
    (
        [0] => 41759.7128
    )