Jump to content
Pardon our ads (a necessary update) ×

Leaderboard

Popular Content

Showing content with the highest reputation since 11/15/2025 in all areas

  1. I agree 100% with @requinix about setting the type of the field to a numeric input. However, I am a belt and suspenders type of programmer. UI constraints are great for helping the user to avoid common data entry errors, but I believe all such validations should have server-side controls (what if the user POSTed a form outside the UI?). The problem is you are making the problem harder than it needs to be. Why do you only care about '£' character? Just because you are accidentally copy/pasting that character doesn't mean you wouldn't have issues with other characters. So, rather than trying to exclude only that specific, arbitrary character - you should remove all characters that would create an invalid number. Or, conversely, you could detect that the value is not a valid number and return the user back to the input page showing an appropriate error. The choice would be a business decision. Taking the first approach, here is one way to do it: function forceToNumber($value) { //Remove everything that is not a digit or decimal point $value = preg_replace('/[^\d.]/', '', $value); //Check if there is more than one decimal point if(substr_count($value, '.') > 1) { //Remove everything from the 2nd decimal $value = substr($value, 0, strpos($value, '.', strpos($value, '.')+1)); } //Retur4n value as a float return (float) $value; } I'm sure there is a more elegant way to deal with possible multiple decimal points (possibly with a single regex), but I've not worked with Regex for quite a while.
    1 point
  2. If the input is supposed to be numbers then help yourself by using an input with type=number so the user can't accidentally type non-digits. Also, it would help to give a visual indication of the currency being implied - typically this looks like a little £ symbol to the left of the input area. The actual problem you're having is 99% likely to be character encoding. There are multiple possible byte encodings of the character "£", and PHP only cares about bytes. So if the £ coming from the form is encoded one way and the £ written in your code is encoded another way, the substitution doesn't happen. Make sure you're using UTF-8 encoding (or some other specific encoding) for absolutely everything - your webpages, your database, your code files, everything. Then you won't have problems with bytes not matching up.
    1 point
This leaderboard is set to New York/GMT-05:00


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.