Home > Mobile >  php prevent sscanf() from assuming '-' as string
php prevent sscanf() from assuming '-' as string

Time:10-18

It can distinguishes between decimal and '-'

$str = "1995-25";
$pat = sscanf( $str , "%d-%d);
print_r($pat);

It can also distinguish first '-' and following string

$str = "-of";
$pattern = sscanf ( $str , "-%s" );
print_r ( $pattern );

but when it comes to signify '-' in middle of a string it assumes '-' as string and more surprisingly the first %s reads it to the last even considering 4 as string

$str = '-of-america-4';
$pat = sscanf ($str , "-%s-%s-%d");
print_r($pat);
// outputs [0] => of-america-4

CodePudding user response:

%s is a greedy match, you could use %[^-]

<?php
$str = '-of-america-4';
$pat = sscanf($str , '-%[^-]-%[^-]-%d');
print_r($pat);
Array
(
    [0] => of
    [1] => america
    [2] => 4
)
  •  Tags:  
  • php
  • Related