FloatChars

FloatChars - Remove all characters except 0-9, +, -, . and optionally ,, e, and E.

FloatChars does not verify if a string is a well-formed float string, it only verifies that all characters belong to a certain character set.
Therefore, even if it's counterintuitive, FloatChars will leave the following strings unmodified:

  • "13"
  • "-50.3"
  • "+-456...789"

FloatChars only works with string, any other type is ignored.

Basic usage

use Jawira\Sanitizer\Filters as Sanitizer;

class User {
  #[Sanitizer\FloatChars]
  public string $height;
}

Parameters

bool allowThousand (optional):
Allow a thousand separator character ,.
Default value is false.
bool allowScientific (optional):
Allow scientific notation characters eE.
Default value is false.

Examples

Only allow 0-9, +, - and . characters.

use Jawira\Sanitizer\Filters as Sanitizer;

class Car {
  #[Sanitizer\FloatChars]
  public string $odometer;
}
"152"     → "152"
"-21"     → "-21"
" +13.5 " → "+13.5"
"437.50X" → "437.50"
"Foo Bar" → ""
"-654-.-546-" → "-654-.-546-"

Only allow 0-9, +, -, ., and thousand separator ,.

use Jawira\Sanitizer\Filters as Sanitizer;

class Car {
  #[Sanitizer\FloatChars(allowThousand: true)]
  public string $odometer;
}
"45,452.3"  → "45,452.3"
"-3,500.50" → "-3,500.50"
"Foo Bar"   → ""
"-654,.,546-" → "-654,.,546-"

Only allow 0-9, +, -, ., and scientific notation characters e, E.

use Jawira\Sanitizer\Filters as Sanitizer;

class Car {
  #[Sanitizer\FloatChars(allowScientific: true)]
  public string $odometer;
}
"15e6"     → "15e6"
"173E-5"     → "173E-5"
"Foo 33 Bar" → "33"
"-+E123..." → "-+E123..."

See also

IntegerChars - Remove all characters except 0-9, +, -, and ..