2012-07-20 74 views
1

我有一個字符串和格式的子字符串,例如「Hello world!%1,abcdef%2,gfgf%14」,即子字符串的格式是'%'+ digit(0 ... infinity),我需要在任何字符串中獲得此子字符串的計數。我知道substring_count函數,但是對於這個函數我需要知道一個定義的行。所以,請告訴我,如何使用正則表達式或其他任何東西來計數?如何使用正則表達式獲取字符串中的子串數?

編輯:

此代碼:

$r = "Hello world!%1, abcdef%2, gfgf%14"; 

$matches = array(); 
preg_match_all('/\%\d+/', $r, $matches); 
echo isset($matches[0]) ? count($matches[0]) : 0; 

但是,如果我有1%之前或之後有一個空格,該代碼不起作用。請修復這個表達。提前致謝。

+0

你所說的 「定義線」 呢?你的輸入字符串是多行的,而且你想知道每個匹配事件的行號? – complex857 2012-07-20 13:25:37

+0

向我們展示您的代碼以及您嘗試的內容。 – Jocelyn 2012-07-20 13:26:53

+0

我的意思是substring_count()我必須輸入「%1」或任何其他的搜索,但我知道只有格式 - 「%」+數字。 – user1538002 2012-07-20 13:28:00

回答

-1

與$使用preg_match_all匹配陣列(第三個參數),然後計算OCCURENCES的長度或數組:

$r = "Hello world!%1, abcdef%2, gfgf%14"; 

$matches = array(); 
preg_match_all('/\%\d+/', $r, $matches); 
echo isset($matches[0]) ? count($matches[0]) : 0; 
+0

有一點請修改您的表達式左右空格,例如「give me%1 and%2」 – user1538002 2012-07-20 13:58:13

+0

您的意思是空格必須存在於雙方還是可能存在?當前腳本說「給我%1和%2」有2次出現。可能存在 – Miroshko 2012-07-20 14:03:41

+0

...現在表達式不能與空格一起使用。 – user1538002 2012-07-20 14:13:48

0

如果你將永遠不會使用%符號比在我的腦海裏確定一個子以外的任何最簡單的方法是做到這一點:

$pieces = explode('%',$string); 
$num_substrings = count($pieces) + 1; 
2
<?php 

$str = "Hello world!%1, abcdef%2, gfgf%14"; 

$match_count = preg_match_all("/%\d+/", $str); 

echo $match_count; 

順便說一句,$matches將保留所有的匹配的子字符串。

0

preg_match_all返回匹配的數目。

$r = "Hello world!%1, abcdef%2, gfgf%14"; 
echo preg_match_all('/\%\d+/', $r, $matches); 
// in PHP >= 5.4 you can leave out $matches 

結果:

3 
相關問題