2013-07-05 43 views
1

我試圖在行內逐行計算所有<img>標記,但無法弄清楚。 我已經做了一行一行地分割字符串,然後在它後面計數<img>標籤。按行逐行計算img標籤

例子:

$string = " 
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text \n 
some text <img src="" /> some text `<img src="" /> some text <img src="" /> some text "; 

現在我的代碼是 首先由線

$array = explode("\n", $string); 

線分割​​,現在指望有多少<img>標籤VAR串的第一線的存在。

$first_line = $array['0']; 

我正在使用preg_match()來獲得img標籤的匹配。

$img_line = preg_match("#<img.+>#U", $array['0']); 
echo count($img_line); 

對我來說這不會工作,在$字符串有3 <img src="">每行,但我的代碼給了我只有1

任何暗示或提示的高度讚賞。

回答

1

如果你做一個簡單的explode一行行,這會給你的計數:

$explode = explode('<img ', $array[0]); 
echo count($explode); 
+0

$ explode = explode(「# #U」,$ array [0]); echo count($ explode);這是以前嘗試的例子。會嘗試你的。 – Vhanjan

+0

@Vhanjan:explode函數只接受一個文字字符串作爲參數,而不是正則表達式。爲了對正則表達式做同樣的處理,使用'preg_split'。 –

+0

@Casimir et Hippolyte:是的,我知道這就是爲什麼我有這個麻煩。但現在我得到了它,我使用preg_match_all。 – Vhanjan

0

明白了..

分割每行後弦。

$first_line = $array['0']; 
$match = preg_match_all("#<img.+>#U", $first_line, $matches); 
print_r($matches); 
echo count($matches['0']); 

上面的代碼將返回這個..

Array 
    (
     [0] => Array 
      (
       [0] => 
       [1] => 
       [2] => 
      ) 
    ) 

3 
+0

請注意,你可以使用這種更好的模式:'#] *>#'(不需要使用貪婪/懶惰的切換器,少用回溯) –

+0

@Casimir et Hippolyte:在正則表達式中+表示可選的權限?但我對此感到困惑[^]。對不起有一些與正則表達式有關的知識。 – Vhanjan

+0

'*'表示零次或多次。 「+」表示一次或多次。 '[^>]'表示所有字符,但是'>'。否定字符類是有用的。 –

0

你可以試試下面的代碼:

<?php 
$string = <<<TXT 
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text 
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text 
TXT; 

$lines = explode("\n", $string); 
// For each line 
$count = array_map(function ($v) { 
    // If one or more img tag are found 
    if (preg_match_all('#<img [^>]*>#i', $v, $matches, PREG_SET_ORDER)) { 
    // We return the count of tags. 
    return count($matches); 
    } 
}, $lines); 

/* 
Array 
(
    [0] => 3 // Line 1 
    [1] => 3 // Line 2 
) 
*/ 
print_r($count); 

這裏,PREG_SET_ORDER結果存入一個級別(第一捕捉索引$matches[0],第二次捕獲到索引$matches[1])。因此,我們可以輕鬆檢索漁獲量。

0
<?php 

$string = 'some text <img src="" /> some text <img src="" /> some text <img src="" /> some text \n 
some text <img src="" /> some text `<img src="" /> some text <img src="" /> some text '; 

$count = preg_match_all("/<img/is", $string, $matches); 

echo $count; 

?> 
+0

您的解決方案計算整個文本中標籤的出現次數,然而@Vhanjan希望每行計數。 – piouPiouM