yerine yerine, php regex maç dönmek nasıl

1 Cevap php

Bu gibi HTML bir metin bloğu içinde bir resmin ilk src niteliğini ayıklamak çalışıyorum:

Lorem ipsum <img src="http://example.com/img.jpg" />consequat.

Ben hiçbir sorun src niteliğini maç için regex oluştururken var, ama nasıl yapmak I return eşleşen birinci src niteliği, yerine replacing bunu?

PHP kılavuzda üzerinden dökülen itibaren, preg_filter() hile yapacağını gibi görünüyor, ama ben PHP> 5.3 olan son kullanıcılar güvenemez.

Tüm diğer PHP regex fonksiyonları şey ile maçı yerine bir boolean değeri veya preg_replace, dönen, preg_match () varyasyonları gibi görünüyor. PHP return bir regex maç için basit bir yolu var mı?

1 Cevap

Sen üçüncü parametresini kullanabilirsiniz preg_match , to know what was matches (It's an array, passed by reference):

int preg_match  ( string $pattern  , 
    string $subject  [, array &$matches  [, 
    int $flags  [, int $offset  ]]] )

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.


For instance, with this portion of code :

$str = 'Lorem ipsum dolor sit amet, adipisicing <img src="http://example.com/img.jpg" />consequat.';

$matches = array();
if (preg_match('#<img src="(.*?)" />#', $str, $matches)) {
    var_dump($matches);
}

Bu çıktıyı alırsınız:

array
  0 => string '<img src="http://example.com/img.jpg" />' (length=37)
  1 => string 'http://example.com/img.jpg' (length=23)

(Note that my regex is overly simplistic -- and that regex are generally not "the right tool" when it comes to extracting data from some HTML string... )