Istiak Mahmood
Istiak Mahmood

Reputation: 2422

detect if there is any negative number in the input

i am trying to detect in php to check if there is any negative number into the input.

I know if the input is just a number, than it is easy to check, but when there is string with the number, how is it possible to check.

example --- "This is a negative number -99" 

So now how is it possible to check that there is a negative number in that line.

I am trying like so, but there is no success ---

$post_data = "This is -12";

if (preg_match('/^\d+$/D', $post_data) && ($post_data < 0)) {
  echo "negetive integer!";
} else {
  echo 'not working';
}

Expected Result --

 Detect if there is any -number like -1, -5, -15 .....

Anyone knows how to solve this problem !!!

Upvotes: 0

Views: 257

Answers (2)

Amrinder Singh
Amrinder Singh

Reputation: 5492

Try this:

<?php
$string="9, -1, -5, 11, 19, 22, -8";
$data=explode(",",$string);
$neg_values=array();
foreach($data as $value):
    $value = preg_replace('/\s+/', '', $value); // to remove space
    if($value < 0):
        $neg_values[]=$value;
    endif;
endforeach;
?>

now print $neg_values, you will get the required output. :)

Upvotes: 0

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

Try this:

if (preg_match('/\-[\d]+/', $post_data)){
    echo "negetive integer!";
} else {
    echo 'not working';
}

First of all, you are using ^ which means that the digit should be at the starting of the string which is not the case here. So we remove it first. then we remove the $ sign as well becasue the negative number can appear anywhere in the string and not just at the end. Next we use a hyphen(-) to tell the regex that the digit should have a minus sign as a prefix to flag it as negative.

Upvotes: 5

Related Questions