2

I want to find integer value using preg_match (PHP) from following string value. I am using following code to find integer value, it works fine for positive integer but I need for positive and negative both. Can anyone help me??

String Value: Hint: Status: -1 Response: Goodbye Message: Thanks for all the fish.

preg_match code so far:

preg_match('/Status: (\d+)/', $queueinfo, $status1 );

4 Answers 4

2

Your code is almost there:

preg_match('/Status: (\d+)/', $queueinfo, $status1 );

The only thing you need to add is the optional dash prefix:

preg_match('/Status: (-?\d+)/', $queueinfo, $status1 );
1
$queueinfo  = 'Hint: Status: -1 Response: Goodbye Message: Thanks for all the fish.';
preg_match('/Status:\s*(?P<status>\-?\d+)/', $queueinfo, $match );  

echo $match['status'];
0
0

Give it a try:

preg_match('/Status\:\s(\-?)(\d+)/', $queueinfo, $m);
$status1 = (int)($m[1].$m[2]);
1
  • 1
    Why not just do /Status: (-?\d+)/ and then $m[1] no need to typecast as well since it is a numeric string otherwise regex would not have matched it.
    – kittycat
    Feb 25, 2013 at 7:06
0
<?php
preg_match_all('/-\d+|(?!-)\d+/', 'String Value: Hint: Status: -1 Response: 12588 Goodbye Message: Thanks for all the fish.', $status1 );
print_r($status1);
?>

Array ( [0] => Array ( [0] => -1 [1] => 12588 ) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.