Home > Enterprise >  Get specific String in String
Get specific String in String

Time:02-21

i have string like this:

hdahdsa jkasdhjsa USD 15,000 jshads hduasdo SN : 02604800000734987654 at  17/02/2022 18:04:47. Blabla bla bla sdsad dsada 

i have tried like this:

$string = "hdahdsa jkasdhjsa USD 15,000 jshads hduasdo SN : 02604800000734987654 at  17/02/2022 18:04:47. Blabla bla bla sdsad dsada "
$array = explode(" ", $string);
foreach ($array as $text) {
    if(is_numeric($text)){
        $sn = $text;
                    }
}

only get $sn = 02604800000734987654

what is the best way get string like this?

$price = 15,000
$sn = 02604800000734987654

CodePudding user response:

is_numeric will return true for an integer (15) or a float (15.00) but 15,000 is neither of those.

A quick fix would be to remove all commas before testing like so :

$matches = array();
$string = "hdahdsa jkasdhjsa USD 15,000 jshads hduasdo SN : 02604800000734987654 at  17/02/2022 18:04:47. Blabla bla bla sdsad dsada ";
$array = explode(" ", $string);
foreach ($array as $text) {
    if(is_numeric(str_replace(',', '', $text))){
        $matches[] = $text;
                    }
}
print_r($matches);
$price = $matches[0];
$sn = $matches[1];

Another solution would be to use regex pattern like

$matches = array();
preg_match('/^[\s\S]  ([0-9,] ) [\s\S]  ([0-9] ) [\s\S] $/m', $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

$price = $matches[1][0];
$sn = $matches[2][0];
  • Related