2011-11-04 260 views
0

防爆幫助:Found: 84 Displaying: 1 - 84PHP:請使用的preg_match

我想preg_match走出數84FoundDisplaying之間,但我在正則表達式非常糟糕。

你知道什麼好的教程來學習正則表達式嗎?我在Google上找不到一個好的。

編輯從下面的評論插入

我這裏只是簡化了我的問題。真正的問題,我會發現它在一個完整的HTML頁面,如谷歌搜索。你知道我的意思嗎?

+3

你一定找到http://www.regular-expressions.info/ –

+0

_現在你有兩個問題... _ http://www.codinghorror.com/blog/2008/06/regular-expressions-now -you-have-two-problems.html :) –

回答

3

如果您的輸入始終採用相同的格式,則無需使用正則表達式。相反,只是在分割空間的字符串:

// explode() on spaces, returning at most 2 array elements. 
$parts = explode(" ", "Found: 84 Displaying: 1 - 84", 2); 
echo $parts[1]; 

更新如果你真的真的真的想用preg_match()這一點,這裏的如何。這不是建議這樣簡單的應用程序。

// Array will hold matched results 
$matches = array(); 

$input = "Found: 84 Displaying: 1 - 84"; 

// Your regex will match the pattern ([0-9]+) (one or more digits, between Found and Displaying 
$result = preg_match("/^Found: ([0-9]+) Displaying/", $input, $matches); 

// See what's inside your $matches array 
print_r($matches); 

// The number you want should be in $matches[1], the first subgroup captured 
echo $matches[1]; 
+0

偏題:我覺得很多「正則表達式」的問題可以通過分割和找到結果來充分回答。 –

+0

好主意,但我仍然想知道如何使用preg_match :-)謝謝。 – Quy

+2

@JaredFarrish如果每次我回答'explode()'到一個正則表達式問題時我都有一美元......(我每個人都有10-20個代表,但它不一樣:)) –

1

相當簡單的正則表達式,我包括使用它的PHP代碼:

<?php 
preg_match("/(\d+)/", "Found: 84 Displaying: 1 - 84", $matches); 
//$matches[0] should have the first number, i.e. 84 
echo $matches[0]; // outputs "84" 
?> 

http://www.regular-expressions.info/有關於如何寫正則表達式一些很好的信息。

編輯:如前所述,在這種情況下正則表達式是矯枉過正的,標記化工作正常。

+0

效果很好。謝謝 – Quy