-2

Possible Duplicate:
regex to wrap img tag with href containg the src

as topic stands - i want to convert all imgages in links based on those images

so:

<img src="http://xxx.xxx/image.jpg"> or <img src="/image.jpg">

<- on local images

converts to:

<a href="http://xxx.xxx/image.jpg"><img src="http://xxx.xxx/image.jpg"></a>

in php

any tips?

Community
  • 1
  • 1
Krzysztof
  • 189
  • 1
  • 10
  • how did i miss it x.x i swear i spent over last 3h searching for it - including good 1h on stackoverflow - anyway thanks for linking - im fairly sure it will do the job:) – Krzysztof Nov 16 '12 at 01:00

4 Answers4

0

Look for:

(\<img\s+src\s*\=\")([^\"]+)(\"\/?\>)

and replace with:

<a href="$2">$1$2$3</a>
Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45
0

If you want to parse HTML output for this you could do (untested)

$out = preg_replace( '/<img .*src="([^"]+)".*>/', '<a href="$1">$0</a>', $input );
Michel Feldheim
  • 17,625
  • 5
  • 60
  • 77
0

So basically you want to add a base_url to your img src right? If you got an array of links(let's say $image_links) you'd do it like that:

foreach($image_links as $image_link) {
    echo '<a href="'.$base_url.'/'.$image_link.'"'.'><img src="'.$base_url.'/'.$image_link.'"'.'></a>';
}
Evo_x
  • 2,997
  • 5
  • 24
  • 40
  • not really...:( i have html source in $string, and i want to convert all images inside to links based on those images. but mario pointed me to the right direction:) – Krzysztof Nov 16 '12 at 00:59
0

Do you really need to do this in php? I think it will be simplier to just use jquery to attach a click event to the images to redirect the browser to the image url when the user clicks the image. It should only take less then 10 lines of javascript totdo so.

iWantSimpleLife
  • 1,944
  • 14
  • 22