1

次のような文字列の例があります

$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';

最初の 3 つの画像の URL を抽出できるようにしたい (基本的に、文字列の先頭にある画像の数は何でも) が、画像以外のテキストが開始されたら、画像の URL を抽出したくありません。正規表現を使用してすべての画像 URL を正常に取得できますが、テキスト内にある最後の google.com 画像も取得します。

アイデアをありがとう!!

4

2 に答える 2

2

画像の URL を取得するために R を正規表現にします

(R)+ を取得する必要があります。つまり、R の 0 回以上の出現

またはほとんど ((R)(w)?)+

w は、空白に一致する正規表現を表します。

于 2012-06-23T22:31:29.193 に答える
1

正規表現を避けて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での例

于 2012-06-23T22:31:50.810 に答える