I have a string, inside of that I have an image:
"<img src="img/programacao/51.jpg" style="width:200px;" /><p>balbalba</p><img src="img/programacao/46.jpg" style="width:200px;" /><p>balbalba</p><img src="/img/finalCinerio.jpg"><p>balbalba</p><img src="img/topo.jpg" />"
I just need the folder of images :img/programacao/
But my regex not working:
preg_match_all('/<img.*?src="([^"]*)"[^>]*>(?:<img>)?/', $text, $image);
Output
...
[0] => img/topo.jpg
[1] => img/p_veneza.png
[2] => img/programacao/51.jpg
[3] => img/programacao/46.jpg
[4] => img/p_rio.png
[5] => /img/finalCinerio.jpg
[6] => img/rodape.jpg
...
But only need it
...
[0] => img/programacao/51.jpg
[1] => img/programacao/46.jpg
...
Easy beasy
'/src=\"(?P<src>img\/programacao\/[^\"]+)\"/'
You don't really need the img
tag unless you have a lot of iframes
or style/script
tags. You can add it in but it makes reliably matching much, much harder. The reason is there is no guarantee where the src
attribute will show.
Most of this is pretty simple, literal matches
[^\"]+
= Not a quote ( match more then one ) matches any sequence that is not a quote. I prefer this then the.*?
match anything un-greedy for readability mostly?P<src>
named( ... )
capture group, return matches with a string key ofsrc
I love named capture groups, although not as useful here with a single match. However, it's main purpose is readability and it allows you to change your code latter. Such as adding another capture group and not worry about the match number changing on you, for example.
If you want to get really fancy
\<img.*?(?<!src=)src=(?P<quote>\"|\')(?P<src>img\/programacao\/[^\k<quote>]+)\k<quote>
(?<!src=)
negative look behind match anything.*?
(non-greedy) if notsrc=
\k<quote>
back reference to the quote capture group, basically means the quote style'
vs"
must match
Although to be honest it's probably overkill.
You could also use preg_match_all
for this, but it depends how you read the file. If you are reading it line for line then use preg_match.
You could do this with a parser and a simple regex to check the attribute starts with required directory...
$string = '<img src="img/programacao/51.jpg" style="width:200px;" /><p>balbalba</p><img src="img/programacao/46.jpg" style="width:200px;" /><p>balbalba</p><img src="/img/finalCinerio.jpg"><p>balbalba</p><img src="img/topo.jpg" />';
$doc = new DOMDocument();
$doc->loadHTML($string);
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) {
if(preg_match('~^img/programacao/~', $image->getAttribute('src'))) {
echo $image->getAttribute('src') . "\n";
}
}
Output:
img/programacao/51.jpg
img/programacao/46.jpg
来源:https://stackoverflow.com/questions/32020171/regular-expression-to-find-all-src-attribute-of-html-img-element-only-folder