Phil Newby
Phil Newby

Reputation: 131

Using php preg to find url and replace it with a second url

I've got a large number of webpages stored in an MySQL database.

Most of these pages contain at least one (and occasionally two) entries like this...

<a href="http://first-url-which-always-ends-with-a-slash/">
  <img src="http://second-different-url-which-always-ends-with.jpg" />
</a>

I'd like to just set up a little php loop to go through all the entires replacing the first url with a copy of the second url for that entry.

How can I use preg to:

  1. find the second url from the image tag
  2. replace the first url in the a tag, with a copy of the second url

Is this possible?

Upvotes: 0

Views: 143

Answers (3)

Phil Newby
Phil Newby

Reputation: 131

Thanks for the suggestions i can see how they are better than using Preg.

Even so i finally solved my own question like this...

$result = mysql_query($select);
while ($frow = mysql_fetch_array($result)) {
    $page_content = $frow['page_content'];

    preg_match("#<img\s+src\s*=\s*([\"']+http://[^\"']*\.jpg[\"']+)#i", $page_content, $matches1);
    print_r($matches1);
    $imageURL = $matches1[1] ; 

    preg_match("#<a\s+(?:[^\"'>]+|\"[^\"]*\"|'[^']*')*href\s*=\s(\"http://[^\"]+/\"|'http://[^']+/')#i", $page_content, $matches2);
    print_r( $matches2 );  
    $linkURL = $matches2[1] ;

    $finalpage=str_replace($linkURL, $imageURL, $page_content) ;
}

Upvotes: 0

Atul Rai
Atul Rai

Reputation: 350

You can do following :

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$source = "<a href=\"http://first-url-which-always-ends-with-a-slash/\">
  <img src=\"http://second-different-url-which-always-ends-with.jpg\" />
</a>";
$dom->loadHTML($source);
$tags = $dom->getElementsByTagName('a');

foreach ($tags as $tag) {
  $atag = $tag->getAttribute('href');  
  $imgTag = $dom->getElementsByTagName('img');
  foreach ($imgTag as $img) {        
    $img->setAttribute('src', $atag);
    echo $img->getAttribute('src');
  }
}

Upvotes: 0

Abid Hussain
Abid Hussain

Reputation: 7762

see this url

PHP preg match / replace?

see also:- http://php.net/manual/en/function.preg-replace.php

$qp = qp($html);
foreach ($qp->find("img") as $img) {
    $img->attr("title", $img->attr("alt"));
}
print $qp->writeHTML();

Though it might be feasible in this simple case to resort to an regex:

preg_replace('#(<img\s[^>]*)(\balt=)("[^"]+")#', '$1$2$3 title=$3', $h);

(It would make more sense to use preg_replace_callback to ensure no title= attribute is present yet.)

Upvotes: 1

Related Questions