regex for currency (euro) - php

i am trying this code for make a validation for a value. (regex from this site)
UPDATE:
Now i have
$value1=250;
$value2=10000;
if (!preg_match("/^(([^0]{1})([0-9])*|(0{1}))(\,\d{2}){0,1}€?$/", $form['salary']) || (!$form['salary'])>$value1."€" && (!$form['salary'])<$value2."€" ){
echo ("invalido");
return false;
}
else
echo ("valido");
return true;
the code works well, but 20€ is accepted, so the problem now is not the regex, but compare values like 200€ or 1000€.
this probably is wrong
(!$form['salary'])>$value1."€"
example some Input values:
200€
200
200.5
200.50€
limits - 250€ to 10000€
thanks

This code below solved my problem:
if (!preg_match("/^(([^0]{1})([0-9])*|(0{1}))(\,\d{2}){0,1}€?$/", $form['salary'])) {
echo "invalid";
return false;
} else {
$value1 = 400;
$value2 = 10000;
$salary = $form['salary'];
$salary = preg_replace('/[€]/i', '', $salary);
if($salary < $value1 || $salary > $value2) {
echo "bad values";
return false;
} else {
echo "valid";
return true;
}
}

The regex solution would look like this
^(?:10000|(?:(?:(?:2[5-9]\d)|[3-9]\d{2}|\d{4})(?:[,.]\d{2})?))€?$
See here online on Regexr
But it would be better for checking if a value belongs to a range, not to use a regex. You can extract the value easily and do a normal <> check on numbers outside.

My contribution. It works great.
final Pattern pattern = Pattern.compile("^([0-9]+)|((([1-9][0-9]*)|([0-9]))([.,])[0-9]{1,2})$");

Related

Preg allowing Blank records

I have the below code for matching an email address using regular expression rules.
It works well, but I've recently noticed that it seems to match a "Blank" email address.
if (preg_match("/.* <.*#.*\..*>/i",$this->to,$matches)) {
$this->email_to = preg_replace("/.*<(.*)>.*/","$1",$this->to);
} else {
$this->email_to = $this->to;
}
My understanding of the preg_match is:-
Looks for any character, except a line break
< anycharacter#anything.anything >
Case-insensitive?
Following those rules, I can't quite work out why it matches a blank / no email address if someone can give some guidance.
Thank you.
No needs for preg_match + preg_replace.
if (empty($this->to)) {
$this->email_to = 'Is empty'; # assign what you want
} elseif (preg_match("/<(.+?#.+?\..+?)>/", $this->to, $matches)) {
$this->email_to = $matches[1];
} else {
$this->email_to = $this->to;
}
I don't know why it behaves like that but an easy solution is to ask if the string is blank
if (preg_match("/.* <.*#.*\..*>/i",$this->to,$matches)) {
if ($matches != ""){
$this->email_to = preg_replace("/.*<(.*)>.*/","$1",$this->to);
} else { $this->email_to = $this->to; }
} else {
$this->email_to = $this->to;
}

How to write preg_match for price

I need a function which check string which is basically price of an item. And it must be like 1-5 characters,2 characters.
Example:
99,99€ == GOOD
99,9€ == BAD
999999,99€ == BAD
Regards!
if (preg_match("~^\\d{1,5}+(:\\,\\d{1,2})$~", $number)) {
return true;
} else {
return false;
}
This will work best for price.
Don't forget you must not allow prices starting with more than one 0 like 000,99 or 0999,99
if(preg_match('/^(?:0|[1-9]\d*)(?:\,\d{2})?$/', $number))
{
return true;
}
else
{
return false;
}
Try this....
<?php
$regex = '/^[\d]{1,5},[\d]{2}$/';
$price = '12321,12';
var_dump( preg_match($regex, $price) );

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

isset $_post issue with mysql query

I'm just working on the Backend of a project an have a small problem with this snippet
if (isset($_POST['id'])) {
$cat_delete = "DELETE FROM category WHERE categoryid='".$_POST['id']."' ";
$cat_delete_ex = mysql_query($cat_delete);}`
But if the id is set with post, nothing happens.
The mysql query is working when I delete the
if (isset($_POST['id']))
anyone have an idea ?
Well I am not sure if your method is safe or not, but I would do it like this, might even throw in a regex to check for just numbers if the id is numeric:
EDIT: I made a revision, since you are dealing with an ID, I will assume the ID is numeric only, so instead of escaping it, I just will strip out everything but numbers. This may be a better fit for your situation. I also converted the function to a class so you will be able to reuse the script for several types of sanitizing strings. Maybe its because I am an overachiever too, I don't know. ADD, OCD, etc. Blame it on that :)
$postID = isset($_POST['id']) ? sanitize::ID($_POST['id']) : '';
if (sanitize::email("test#example.com")){
echo "Real email";
} else {
echo "Fake email";
}
if ($postID != ''){
$cat_delete = "DELETE FROM category WHERE categoryid='".$postID."' ";
$cat_delete_ex = mysql_query($cat_delete);
}
class sanitize{
function ID($string){
$string = preg_replace('/[^0-9,]|,[0-9]*$/','',$string);
return $string;
}
# I added another sanitize function so you can see what you can do
# with it. Add phone numbers, domain names, etc... Each one could
# be called with sanitize::{FUNCTION}
function email($string){
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $string)) {
return false;
}
$email_array = explode("#", $string);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",$local_array[$i])) return false;
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) return false;
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) return false;
}
}
return true;
}
}
are you sure you are using post for the id?(asking because is the right way, but i have one too many times
<form action="action.php?id=hereistheid"
which will bring the id in the $_GET not $_POST.
next the checking
$id=(int)$_POST['id'];
if($id)
{
//do smth
}

Detecting negative numbers

I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}

Categories