-3

How can i find all image links using "preg_replace"? I've hard time understanding how to implement regex

what I've tried so far:

$pattern = '~(http://pics.-[^0-9]*.jpg)(http://pics.-[^0-9]*.jpg)(</a>)~';
$result = preg_replace($pattern, '$2', $content);
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Crazy_Bash
  • 1,755
  • 10
  • 26
  • 38

2 Answers2

3

preg_replace(), as the name suggests, replaces something. You want to use preg_match_all().

<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[2] . "\n";
    echo "part 3: " . $val[3] . "\n";
    echo "part 4: " . $val[4] . "\n\n";
}
Flavius
  • 13,566
  • 13
  • 80
  • 126
2

another easy way to find all images link from web page, use simple html dom parser

// Create DOM from URL or file

$html = file_get_html('http://www.google.com/');

// Find all images

foreach($html->find('img') as $element) 
echo $element->src . '<br>';

this is so simple way to get all image link from any webpage.

Jaydipsinh
  • 491
  • 1
  • 9
  • 27