我想從以下字符串值中使用preg_match(PHP)查找整數值。我使用下面的代碼來查找整數值,它對正整數工作正常,但我需要正面和負面的兩個。誰能幫我??如何使用preg_match從字符串獲取整數值php
字符串值:提示:狀態:-1回覆:再見消息:感謝所有的魚。
的preg_match迄今代碼:
preg_match('/Status: (\d+)/', $queueinfo, $status1);
我想從以下字符串值中使用preg_match(PHP)查找整數值。我使用下面的代碼來查找整數值,它對正整數工作正常,但我需要正面和負面的兩個。誰能幫我??如何使用preg_match從字符串獲取整數值php
字符串值:提示:狀態:-1回覆:再見消息:感謝所有的魚。
的preg_match迄今代碼:
preg_match('/Status: (\d+)/', $queueinfo, $status1);
試試看:
preg_match('/Status\:\s(\-?)(\d+)/', $queueinfo, $m);
$status1 = (int)($m[1].$m[2]);
$queueinfo = 'Hint: Status: -1 Response: Goodbye Message: Thanks for all the fish.';
preg_match('/Status:\s*(?P<status>\-?\d+)/', $queueinfo, $match);
echo $match['status'];
編輯代碼請現在檢查 – 2013-02-25 06:55:50
<?php
preg_match_all('/-\d+|(?!-)\d+/', 'String Value: Hint: Status: -1 Response: 12588 Goodbye Message: Thanks for all the fish.', $status1);
print_r($status1);
?>
陣列([0] =>數組([0] => -1 [1] => 12588))
你的代碼幾乎在那裏:
preg_match('/Status: (\d+)/', $queueinfo, $status1);
需要添加的唯一事情是可選的破折號前綴:
preg_match('/Status: (-?\d+)/', $queueinfo, $status1);
爲什麼不只是做'/狀態:( - ?\ d +)/'然後'$ M [1]'不需要類型轉換,因爲它是一個數字字符串,否則正則表達式不會匹配它。 – 2013-02-25 07:06:53
是的,它更好! – k102 2013-02-25 09:07:51