È possibile togliere un carattere specifico utilizzando str_replace
, e lanciato come un intero utilizzando intval
. È anche possibile utilizzare un filtro di espressioni regolari per determinare se la stringa di input è formattata correttamente. Ecco come potrebbe essere il codice:
<?php
function remove_delimiters_simple($string, $delimiter = ',') {
// Removes all instances of the specified delimiter and cast as an integer
// Comma (,) is the default delimiter
return (int) str_replace($delimiter, '', $string);
}
function remove_delimiters_advanced($string, $delimiter = ',') {
// Use preg_quote in case our delimiter is '/' for some reason
// The regular expression should match validly formatted numbers using a delimiter
// every 3 characters
$valid_format_expression = sprintf(
'/^\d{1,3}(%s\d{3})*$/',
preg_quote($delimiter, '/')
);
// If not a validly formatted number, return null
if (! preg_match($valid_format_expression, $string)) {
return null;
}
// Otherwise, return the simple value
return remove_delimiters_simple($string, $delimiter);
}
è troppo ampio, che ne dici di altri casi di test? '1,000.456' – Ghost
aggiornato. Grazie – paullb