【问题标题】:Is it possible to get image URLs from the start of a string in PHP?是否可以从 PHP 中的字符串开头获取图像 URL?
【发布时间】:2012-06-23 22:27:08
【问题描述】:

我有一个示例字符串如下

$string = '
http://image.gsfc.nasa.gov/image/image_launch_a5.jpg
http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg
http://image.gsfc.nasa.gov/image/image_launch_a5.jpg

Alot of text

http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif

more text';

我希望能够提取前三个图像的 url(基本上是字符串开头的任何图像#),但在我的非图像文本开始后不提取任何图像 URL。我可以成功地使用正则表达式来抓取所有图片 URL,但它也抓取了文本内的最后一个 google.com 图像。

感谢您的任何想法!

【问题讨论】:

  • 尝试搜索。以前已经这样做过。很多次。但是,如果你可以抓住所有(如帖子中所声称的)那么这只是一小步,1)在 X 之后停止抓取(改变你已经拥有的方法)或 2)抓住 N 然后只“采取/使用”X(使用您已经拥有的方法,并且仅使用结果数据的子集)
  • @pst N 未知,字符串开头可能有 1 个图像或 10 个图像,这是我的问题,否则我将通过简单的正则表达式获取前 3 个图像
  • 参见 #1 和 #2。他们不会改变。调整你所拥有的。

标签: php regex image parsing


【解决方案1】:

让 R 为正则表达式以获取图像 url

您需要抓住 (R)+ ,即出现 0 次或多次 R

或主要是 ((R)(w)?)+

其中 w 表示匹配空格的正则表达式。

【讨论】:

  • 没有花精力写正则表达式,因为你已经说过你可以成功地使用正则表达式来抓取所有的图像URL :)
【解决方案2】:

如何避免使用正则表达式并改用explode

$string = '....';

$urls = array();
$lines = explode(PHP_EOL,$string);
foreach ($lines as $line){
  $line = trim($line);

  // ignore empty lines
  if (strlen($line) === 0) continue;

  $pUrl = parse_url($line);

  // non-valid URLs don't count
  if ($pUrl === false) break;

  // also skip URLs that aren't images
  if (stripos($pUrl['path'],'.jpg') !== (strlen($pUrl['path']) - 4)) break;

  // anything left is a valid URL and an image
  // also, because a non-url fails and we skip empty lines, the first line
  // that isn't an image will break the loop, thus stopping the capture
  $urls[] = $line;
}
var_dump($urls);

IDEOne的示例

【讨论】:

  • 有趣,我真的很喜欢这个主意,我刚插上电源,但它现在抓住了每一行:(
  • @Mark:对此感到抱歉,请尝试改用(答案已更新)。我还利用parse_url 来验证图像 URL。
猜你喜欢
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 2014-01-15
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多