Make Regex Match Just Once

158 views Asked by At

I want to get first src attribute, I am using this regex but it scraping all src attribute:

(?<=src=").*?(?=")

Example:

<img src="http://ia.media-imdb.com/images/M/MV5BMTY3NjY0MTQ0Nl5BMl5BanBnXkFtZTcwMzQ2MTc0Mw@@._V1_SY317_CR0,0,214,317_AL_.jpg" />
<img src="http://ia.media-imdb.com/images/M/MV5BMjAzODk4OTI3Ml5BMl5BanBnXkFtZTgwMzU2MTY0MzE@._V1_SX86_CR0,0,86,86_AL_.jpg" />
<img src="http://ia.media-imdb.com/images/M/MV5BNzUzNzY1NzQxM15BMl5BanBnXkFtZTgwMTM0MTY0MzE@._V1_SY86_CR33,0,86,86_AL_.jpg" />
<img src="http://ia.media-imdb.com/images/M/MV5BMTAxNTAwMTg0ODReQTJeQWpwZ15BbWU4MDMzNDE2NDMx._V1_SY86_CR33,0,86,86_AL_.jpg" />
3

There are 3 answers

2
Avinash Raj On BEST ANSWER

You could get the value of first img src attribute in two ways.

  1. Through capturing group.

    (?s)^(?:(?!<img\b[^<>]*?\bsrc=).)*<img\b[^<>]*?\bsrc="([^"]*)"
    

Grab the value of img src attribute from group index 1.

DEMO

  1. Through \K and positive lookahead assertion.

    (?s)^(?:(?!<img\b[^<>]*?\bsrc=).)*<img\b[^<>]*?\bsrc="\K[^"]*(?=")
    

Grab the value of img src attribute from group index 0.

DEMO

0
vks On
^((?!\bsrc\b).)*src="([^"]+)

Try this.Grab the capture.See demo.

http://regex101.com/r/xN4qL9/3

0
Ahosan Karim Asik On

try this:

  $re = "/src=[\"'](?<src>[^<>\"']+)['\"]/";
    $str = "<img src=\"http://ia.media-imdb.com/images/M/MV5BMTY3NjY0MTQ0Nl5BMl5BanBnXkFtZTcwMzQ2MTc0Mw@@._V1_SY317_CR0,0,214,317_AL_.jpg\" />\n<img src=\"http://ia.media-imdb.com/images/M/MV5BMjAzODk4OTI3Ml5BMl5BanBnXkFtZTgwMzU2MTY0MzE@._V1_SX86_CR0,0,86,86_AL_.jpg\" />\n<img src=\"http://ia.media-imdb.com/images/M/MV5BNzUzNzY1NzQxM15BMl5BanBnXkFtZTgwMTM0MTY0MzE@._V1_SY86_CR33,0,86,86_AL_.jpg\" />\n<img src=\"http://ia.media-imdb.com/images/M/MV5BMTAxNTAwMTg0ODReQTJeQWpwZ15BbWU4MDMzNDE2NDMx._V1_SY86_CR33,0,86,86_AL_.jpg\" />";

    preg_match($re, $str, $matches);
    var_dump( $matches['src']);

output:

string 'http://ia.media-imdb.com/images/M/MV5BMTY3NjY0MTQ0Nl5BMl5BanBnXkFtZTcwMzQ2MTc0Mw@@._V1_SY317_CR0,0,214,317_AL_.jpg' (length=114)

live demo