2013-07-05 48 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