2014-12-05 45 views
0

我有一個字符串,裏面只有一對引號。我怎樣才能得到這個數字使用PHP?在報價單內獲取號碼

我已經嘗試遍歷字符串和或使用str_split,但我不知道如何限制它在引號內。數字可以是任何長度的事實使得它更難。

編輯:下面是一個例子

Hello this is my "100"th string!, 

我需要返回100;

+1

帖子你嘗試過什麼? – MH2K9 2014-12-05 02:26:42

+0

我試過的是廢話,因爲我不知道PHP。如果有人能帶領我走向正確的方向,那將會有所幫助。 – Ogen 2014-12-05 02:28:10

+0

請seee 499,000結果之一[這裏](https://www.google.co.uk/?gws_rd=ssl#q=php+cast+string+to+int) – andrew 2014-12-05 02:30:43

回答

1

preg_match()是一種從字符串中獲取數字的方法。例如:

$str = 'Hello this is my "100"th string!,'; 
preg_match('/\d+/', $str, $match); 

echo $match[0]; 

Demo

+0

有沒有一種簡便的方法來減少字符串中的數字,類似於這個方法?所以它會返回'你好,這是我的「第99」字符串!,' – Ogen 2014-12-05 02:44:03

+0

'str_replace()'一種方式來做到這一點。 'preg_match('/ \ d + /',$ str,$ match); $ str = str_replace($ match [0],$ match [0] - 1,$ str); echo $ str;' – MH2K9 2014-12-05 02:45:46

+0

這個工作很好的正數,但它不適用於負數,因爲負號被忽略,有什麼辦法可以合併負號嗎? – Ogen 2014-12-05 09:59:04

2
echo intval('123string'); 

結果123

1

從字符串周圍修剪的報價和PHP將立即看到裏面的號碼。

$str = "'1234'"; 
$num = trim($str, "'\""); 
echo $num + 1; 
// => 1235 

,或者如果你有文字還有一個字符串,替換所有非數字用空格,然後讓 PHP自動解析字符串時,它在算術表達式中使用。

$num = preg_replace('/\D/', ' ', $string) + 0; 
1

使用的preg_replace:

echo preg_replace("~[^\d+]~", '', 'Hello this is my "100"th string!,');