H
H
hashspark2012-11-08 13:59:37
Regular Expressions
hashspark, 2012-11-08 13:59:37

How to complete a regular expression?

There is a regular expression that determines if there is an image on the page.
'/(img|src)=("|\')[^"\'>]+/im'
How can I fix it so that it detects the presence of two or more pictures? Or get the number of pictures in the text?
Ps you only need to use php.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
akral, 2012-11-08
@hashspark

You shouldn't parse HTML with regular expressions .
But if you really want to, in the above case it is correct to use an external calculation of the results of executing a regular expression for this purpose:

$count = preg_match_all('/(img|src)=("|\')[^"\'>]+/im', $html);
if ($count > 1) ...

I would change the regular expression:
/<img\s+[^>]*src\s*=[^>]+>/i

J
jcmvbkbc, 2012-11-08
@jcmvbkbc

For example '/(<img=.*){2,}/i'

K
KidsKilla, 2012-11-08
@KidsKilla

Like this, for example:

var q = 0, urls = [];
innerHTML.replace(/\s+/, ' ').replace(/(?:\r|\n|\s)+/, ' ').replace(
    /<img(?:.+?)?src=("|')(.+?)\1(?:.+?)?>/i, 
    function(mtch, q, url) {
        urls[q++] = url;
    }
);
alert('Картинок - '+q);

Well, or through RegExp.exec()

D
darkoff, 2013-01-12
@darkoff

If you only need to count pictures, without extracting a link to them, I recommend using

substr_count(<code>, "<img")

int substr_count ( string haystack, string needle )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question