开发者

Modify all img src tags in a particular way

I want to use phpThumb to resize all images in the content divs of my pages when they are served up to mobile devices.

So in my page templates for mobile devices I need to change all <img> tags in <div id="content> in the following manner:

<img src="/images/image_01.jpg">
-> <a href="/images/image_01.gif">
     <img src="phpThumb.php?src=images/image_01.jpg&w=300">
   </a>

<img src="/images/image_02.gif">
-> <a href="/images/image_02.gif">
     <i开发者_StackOverflowmg src="phpThumb.php?src=images/image_02.gif&w=300">
   </a>

What is the best way to do this?


Use str_replace to replace the old img tags to new ones. Alternatively, you can use preg_replace too if you are comfortable with regular expressions.


Since these are template pages specific to mobile devices I would suggest applying this to the actual template file instead of running some PHP code to transform it each time a mobile device requests a page. Most editors have Search & Replace functionality. And some support Regexes. Utilize this to replace all /src="([^"]+)"/ with src="phpThumb.php?src=$1&w=300".


Regular expressions are perfectly fine for that purpose. But you can also use "server-side jQuery" with http://querypath.org/ to transform it like this:

$html = qp($html);
foreach ($html->find("img") as $img) {

     $src = $img->attr("src");
     $img->attr("src", "new.php...");   // redirect to thumbNail

     $img->replaceWith("<a href='$src'>" . $img->html() . "</a>");
}
print $html->writeHTML();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜