PHP:拉取图像并修改其输出
我想对我的图像使用调整大小脚本(蒂姆拇指)。 我试图从数据库中提取帖子中包含的第一个图像,并将脚本的路径以及一些额外的说明添加到其中:
<?php
$content = $post->post_content;
preg_match_all('/src=\"https?:\/\/[\S\w]+\"/i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $e)
echo '<img src="http://site/scripts/timthumb.php?'.$e[0].'&h=320&w=214&zc=1" title="" alt="">';
{
}
?>
虽然这呼应了我所需要的所有内容,但它在中间添加了标签,一些缺少图像路径的双引号(我需要检测图像的相同双引号):
<img src="http://site/scripts/timthumb.php?src="http://site/images/image.jpg"&h=320&w=214&zc=1" title="" alt="">
所以我的问题是:
- 你会如何删除这些 双引号(虽然我需要它们 寻找的第一时刻 图案) ?
- 并且,你会怎么做 只拉帖子中的第一张图片?
非常感谢您的任何意见
I'd like to use a resizing script for my images (Timthumb). I'm trying to pull from the database the first image contained in a post, and add to it the path to the script, as well as some extra instructions :
<?php
$content = $post->post_content;
preg_match_all('/src=\"https?:\/\/[\S\w]+\"/i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $e)
echo '<img src="http://site/scripts/timthumb.php?'.$e[0].'&h=320&w=214&zc=1" title="" alt="">';
{
}
?>
While this is echoing all I need, it adds, in the middle of the tag, some double quotes which are missing the image's path (the same double quotes I need to detect the image):
<img src="http://site/scripts/timthumb.php?src="http://site/images/image.jpg"&h=320&w=214&zc=1" title="" alt="">
So my questions are :
- How would you do to remove those
double quotes (while I need them in
a first moment to search for a
pattern) ? - And, how would you do to
pull only the first image in the post ?
Many thanks for any input
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,使用括号来捕获您需要的部分,即 URL 本身。 其次,如果您只需要第一个图像,则只需使用 preg_match,而不是 preg_match_all:
请注意正则表达式的 URL 部分是如何用 () 标记的 - 因为这是第一个括号表达式,它将是 $match 数组的元素 1。
我还对图像 URL 进行了 urlencode 编码,以确保该匹配中的任何内容都经过正确编码,以便在 URL 中使用。
Firstly, use parentheses to capture just the bit you need, the URL itself. Secondly, if you only need the first image, then just use preg_match, rather than preg_match_all:
Note how the URL part of the regex is marked with () - as this is first bracketed expression, it will be element 1 of $match array.
I've also urlencoded the image URL to ensure that anything in that match is correctly encoded for use in a URL.