Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace <img src="test.jpg" to <a href="test.jpg">

Status
Not open for further replies.

saulensr

Programmer
Mar 29, 2010
3
LT
Hello
I found this function:
function GetImageSource($strHtml)
{
$strRegExp = '/<img (?:.*?)src=(?:"|\'){1}(.*?)(?:"|\'){1}/is';

$arrMatches = array();

$bolMatched = preg_match_all($strRegExp,$strHtml,$arrMatches);

if( $bolMatched!==false && isset($arrMatches[1]) )
{
return $arrMatches[1];
}
else
{
return false;
}
}

How can I replace all <img src="xxxx.jpg" to <a href="xxxx.jpg><img src="xxxx.jpg" ? xxxx.jpg not the same image file. I want replace all <img src="image
 
I ma trying and trying preg_replace() but it dont works for me. I am a little new in complicated php. Can anyone help to me to replace function what i found that she work like replace? Please. I am trying it to do all week but it dont works for me.
 
Hi

Interesting. It works for me.
PHP:
[navy]$html[/navy][teal]=[/teal][COLOR=darkgoldenrod]preg_replace[/color][teal]([/teal][green][i]'/(<img .*?src="(.+?)".*?>)/'[/i][/green][teal],[/teal][green][i]'<a href="\2">\1</a>'[/i][/green][teal],[/teal][navy]$html[/navy][teal]);[/teal]


Feherke.
 
Thank you very much!!!!!!!!!!!!

Its working

You helped for me very much.
 
unless you are doing this as a one off it may be more processor efficient for you to offload this functionality to the browser via javascript.

of course if you are doing this as a one off then a server based solution is best. similarly a javascript will (obviously) not work if a user has js turned off

using jQuery this would be as simple as one of the following solutions.

Code:
/**
 * @author justinadie
 */
$(document).ready(function(){
    $('img[src*=.jpg]').each(function(){
        var u = $(this).attr('src');
        $(this).wrap('<a href="' + u + '">');
    });
});
/* or you could do this instead */
$(document).ready(function(){
    $('img[src*=.jpg]').bind('click', function(e){
        window.open = $(this).attr('src'); // this opens a new window
        /*
         * window.location = $(this).attr('src'); //this opens a the image in the same window
         */
    });
});

and to all readers my apologies for posting a js solution in the php forum. My aim was to point out that php may not be the best tool for this job, in this case.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top