Regex - Strip non numeric and remove cents if any - php

I'm currently working on a project in PHP and I'm in need of some Regex help. I'd like to be able to take a user inputted monetary value and strip all non numeric and decimal places/cents.
Ex:
'2.000,00' to '2000'
'$ 2.000,00' to '2000'
'2abc000' to '2000'
'2.000' to 2000
(I'm using non US currency formatting)
How can I do this? I'd appreciate the help - Thanks

You can do:
$str = preg_replace('/[^0-9,]|,[0-9]*$/','',$str);

$output = preg_replace('/[^0-9]/s', '', $input);
that should replace non numeric chars with empty strings.

This should do what you want.
$your_string_without_letters = preg_replace('\w+', '', $your_string)
preg_match('[0-9][0-9.]*', $your_string_without_letters, $matches);
$clean_string = $matches[0];
The match will start as soon as the first number is found, and stop when it hits something that is neither a number nor a dot (ie. a comma or the end of the string in your examples)
EDIT : forgot to remove the letters inside the value first.
(Just a personal opinion, but if a user writes chracters that are not numbers, dots, commas or currency symbols I would refuse the input instead of trying to clean it)

On the client side I use classes on the inputs:
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
$("input.money").keyup(function(){ money($(this)) })
.blur(function(){ money($(this),1); });
//----------- free-standing functions --------------
function money($inElem,inBlur,inDec){//enforces decimal - only digits and one decimal point. inBlur bool for final slicing to sets of 3 digits comma delimted
var isBlur=inBlur||0;//expects boolean (true/false/0/1 all work), default to 0 (false)
var dec=inDec || 2;
if(/[^,.0-9]/g.test($inElem.val()))//if illegal chars, remove and update
$inElem.val($inElem.val().replace(/[^,.0-9]/g, ""));
var ra=$inElem.val().split(".");
if(ra.length>2 || ra.length>1 && ra[ra.length-1].length>2){//if too more than 1 "." or last segment more than dec digit count, fix and update
if(ra[ra.length-1].length>2) ra[ra.length-1]=ra[ra.length-1].substr(0,dec);//shorten last element to only dec digit count
$inElem.val(ra.slice(0,ra.length-1).join("")+"."+ra[ra.length-1]);//glom all but last elem as single, concat dec pt and last elem
}
if(inBlur){
ra=$inElem.val().split(".");
var rvsStr=zReverse(ra[0].replace(/,/g,""));
var comDelim="";
while(rvsStr.length>0){
comDelim+=rvsStr.substr(0,3)+",";
rvsStr=rvsStr.substr(3);
}
$inElem.val(zReverse(comDelim).substr(1)+(ra.length==2?"."+ra[1]:""));
}
}
function zReverse(inV){//only simple ASCII - breaks "foo 𝌆 bar mañana"
return inV.split("").reverse().join("");
}

Related

PHP search in a variable text and save it

I have this autogenerated variable:
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
How can I search and save "9999" in this var? I cant use substr cause $var's value is always changing and it is always in another "place" in the variable. It is always 4 numbers.
You can match 4 numbers wrapped by word boundaries or space characters, depending on what you need with regular expression (regex/regexp).
if( preg_match('/\b([0-9]{4})\b/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Note, however, that the word boundary match will also match on non-letter characters (symbols like dollar sign ($), hyphen (-), period (.), comma (,), etc.). So a string of "XYZ ABC 9843-AB YZV" would match the "9843". If you want to just match based on numbers surrounded by white space (spaces, tabs, etc) you can use:
if( preg_match('/(?:^|\s)([0-9]{4})(?:\s|$)/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Using explode is the way to go, we need to turn the string into an array, our variables are separated by white space, so we get a variable every time we face a white space " ", i made another example to understand how explode works.
<?php
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
print_r (explode(" ",$var)); //Display the full array.
$var_search = explode(" ",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
<br>
<?php
$var = "WXYZ+300700Z+32011KT+9999+FEW035+SCT200+24/16+Q1007+NOSIG";
print_r (explode("+",$var)); //Display the full array.
$var_search = explode("+",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
I hop this is what you're looking for
Is this viable?
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
if (strpos($var, '9999') == true {
// blah blah
}
else{
echo 'Value not found'
}
Personally haven't tested this yet, but I think you're looking for something along these lines...
Hello I would use a preg_match regex using this regular expression : \d{4}
here is the solution
var str1 = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
var str2 = "9999";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}

Preg_match find numbers in string after Dash [duplicate]

i have a id like stringNumber variable like the one as follows : example12
I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.
This regular expression matches numbers at the end of the string.
var matches = str.match(/\d+$/);
It will return an Array with its 0th element the match, if successful. Otherwise, it will return null.
Before accessing the 0 member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle.
If you must have it as a Number, you can use a function to convert it, such as parseInt().
number = parseInt(number, 10);
RegEx:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
String manipulation:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);

How to remove formatting characters?

I set formatting mask on a textfield :
$(document).ready(function() {
$("#budget_para_prevision").inputmask("9999999999999.99"); // 13 digits before "."
});
The problem happens after posting the form when the length of the digits before the "." sign is less than 13 then the formatting characters are written automatically with the $_POST variable , it gives something like this :
391000000000_.__
So how to remove the _ and the . sign in this case ?
You can remove the unwanted characters using a combination of str_replace and rtrim. Something like this:
$input = "391000000000_.__";
$result = str_replace("_", "", $input); // Remove instances of underscore.
$result = rtrim($result, "."); // Remove the dot if it's the last character.
Or you can just do the whole lot with a single rtrim:
$result = rtrim($input, "._");
You can have part of your mask be optional. Anything listed after '?'
within the mask is considered optional user input. The common example
for this is phone number + optional extension.
$(document).ready(function() {
//if 12 and more digits are optional
$("#budget_para_prevision").inputmask("999999999999?9.99");
});
From docs
I guess it would depend on what jQuery inputmask plugin you are using exactly, but if it is Robin Herbots plugin, you can make parts of your input optional and specify lengths:
$(document).ready(function() {
$("#budget_para_prevision").inputmask("9{1,13}[.99]"); // 13 digits before "."
});
Of course you could also fix it at the backend with rtrim($input, "._") but preventing the input in the first place would be better.

How to check a string for a given format using PHP?

I have many headlines in my project like:
00.00.2014 - Headline Description e.t.c.
I want to check with php if the given strings contain the format 00.00.0000 - in front. The part after the - doesn't matter.
Can someone help me with something like:
$format = '00.00.0000 -';
if ($string MATCHES $format IN FRONT) {
// ...some code...
}
This should work:
if (preg_match("/^\d{2}\.\d{2}\.\d{4}\s\-\s.*$/", $string) === 1) {
// $string matches!
}
Explanation:
^ is "the beginning of the string"
\d is any digit (0, 1, 2, ..., 9)
{n} means "repeated n times"
\. is a dot
\s is a space
\- is a minus sign
. is "any single character"
* means "repeated 0 or more times`
$ means "end of the string"
I don't have a dev environment to test this out on but i'll give you some psuedocode:
I'm unsure of the context, but you can test this function on any given STRING:
Function:
Boolean hasCorrectFormat($myString){
//Here take the string and cut it into a char array.
$charArray = str_split($myString);
//This will give you a char array. Compare the first 12 elements of this
//array to see if they are correct. If its supposed to be number make
//sure it is, if its supposed to be a "." make sure it is..etc
//"00.00.0000 -" is 12 characters.
if(!isNumeric(charArray[0])){
return false;
}
else if(!isNumeric(charArray[1])){
return false;
}
else if(charArray[2] != "."){
return false;
}
//so on and so forth.....
else {return true}
}
Like i said i can't test this, and i can almost guarantee you this code wont run. This should give you the logic involved though.
Edit: also i wrote this assuming you dont literally mean "00.00.0000" but rather "xx.xx.xxxx" x being any number 0-9. If you need to make sure it is literally zeros then just cut your string to be the first ten chars and compare it.
Use the strpos function. Something like this:
if (strpos($string,'00.00.0000 -') !== true) {
//some code
}

How to return false if all numerical values of 0-9 are matching WITH other characters in string?

I am specifically targeting numerical only, So if I am using a phone mask using javascript on front end that filters user input to (000)000-000, basically [2-9] and [0-9] as mask (jquery.maskedinput-1.3.js) and mobile filter...
jQuery(function ($e) {
var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
$e('#refer').val(window.location.href);
if (!(isMobile)) {
$e('#phone').mask('(299)299-9999');
$e('#field_phone_number').mask('299-299-9999');
}
});
For server side I have a regular expression in PHP as (nothing special yet)
function phonenumber($value)
{
return preg_match("/\(?\b[(. ]?[0-9]{3}\)?[). ]?[0-9]{3}[-. ]?[0-9]{4}\b/i", $value);
}
How can a create a regex or php script that targets all numerical values without creating a very long regex for each character? I just want to know if someone types in (222)222-2222, they get a false on the return.
function phonenumber($value)
{
$prefix = '\d{3}'; // You might want to specify '2\d\d' (200 to 299)
$regex = '#^(\('.$prefix.'\)|'.$prefix.')[\s\.-]?\d{3}[\.-]?\d{4}$#';
if (preg_match($regex, $value))
{
// Number is in a suitable format
// Now extract digits -- remove this section to not test repeated pattern
$digits = preg_replace('#[^\d]+#', '', $value);
// All numbers equal are rejected
if (preg_match('#^(\d)\1{9}$#', $digits))
return false;
// end of pattern check
// Otherwise it is accepted
return true;
}
return false; // Not in a recognized format
}
This will accept (299)423-1234 and 277-111-2222, and also (400)1234567 or 4001234567. It will reject (400-1234567 and 400-12-34-56-7. It will also reject (222)222-2222 because of the repeated 2's.
You can use a backreference \1 to detect recurring patterns. In your case you can simply mix in a .* to ignore in-between fillers like ( and -
/(\d)(.*\1){7}/
Will look for a number, and at least 7 repetitions of the same, ignoring any other characters used as filler. This will not ensure that they are consecutive however, so (222)222-8222 would match too.

Categories