문제

Replace all img tag with anchor tag where img src attribute value should be anchor tag href attribute value. I couldn't get idea how to write pattern to match whole and replace img tag and return anchor tag with href value as src attribute value of img tag in following process function.

I have tried below:

$pattern = '/<img[^>]+>/i'; 
$callback_fn = 'process';   
$content = preg_replace_callback($pattern, $callback_fn, $string);
function process($matches) 
{
        print_r($matches);
    return "&nbsp;&nbsp;<a href='http://mywebsite.com/".$matches[0]."'> <font color ='black' >View Image</font>&nbsp;&nbsp;</a>";
}       
echo $content;

for example:

$string = "this is dummy string <img src="imageone.jpg" alt="" /> this is another sentesnces <img src="imagetwo.jpg" /> this is third one";

The output is:

this is dummy string View Image this is another sentesnces View Image this is third one

Here, View Image is link with

http://mywebsite.com/<img src="imageone.jpg" alt="" />

But I want this:

http://mywebsite.com/imageone.jpg
도움이 되었습니까?

해결책

Try like this

$pattern = '/<img.+src=(.)(.*)\1[^>]*>/iU';
$callback_fn = 'process';
$string = 'this is dummy string <img src="imageone.jpg" alt="" /> this is another sentesnces <img src="imagetwo.jpg" /> this is third one';
$content = preg_replace_callback($pattern, $callback_fn, $string);
function process($matches)
{
    return "&nbsp;&nbsp;<a href='http://mywebsite.com/".$matches[2]."'> <font color ='black' >View Image</font>&nbsp;&nbsp;</a>";
}
echo $content;

Also instead of <font> tag, use <span> because <font> is deprecated.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top