Bu dize biçimlendirme ile küçük bir php yardım

4 Cevap

Ben bu biçimde bir dize var:

    /SV/temp_images/766321929_2.jpg

Çizgi ÖNCE numaralarını almak için kod herhangi bir küçük parça var, ANCAK temp_images SONRA /? Bu durumda ben ... 766321929 sadece almak istiyor?

Teşekkürler

4 Cevap

Bu hile yapmak gerekir:

$str = '/SV/temp_images/766321929_2.jpg';
$m = array();
if (preg_match('#temp_images/(\d+)_#', $str, $m)) {
    echo $m[1];
}


The idea :

  • Use preg_match with a regular expression
    • O 'temp_images/' ile başlayan şey ile çalışır
    • ve '_' ile biter
    • ancak olanlar arasında bulunmuştur (\d ile sembolize) numaralarını döndürür
  • And the third parameter, $m, will contain what was matched :
    • $m[0] eşleşti her şey olacak
    • Yani, aradığınızı burada - $m[1] (between ()) bölüm çekilen ilk olacak


And the output :

766321929


And if you're curious and what to know more about regex, don't hesitate to take a look at Regular Expressions (Perl-Compatible) -- there is a lot of interesting stuff to read, there ;-)

Burada kirli bir yoldur:

$contents = ' /SV/temp_images/766321929_2.jpg';
$contents = substr($contents, strpos($contents, 'temp_images/'));
$contents = substr($contents, strpos($contents, '/'));
$contents = substr($contents, 1);
$contents = substr($contents, 0, strpos($contents, '_'));
print $contents;

Bu basename kullanımı ve daha sonra bu gibi explode edilen dosya olabilir ...

$fileComponents = explode('_', basename($filePathString));
$requiredComponent = $fileComponents[0];

O dedi, size gerekli vb gibi aklı denetimi eklemek gerekiyordu.

Genel çözüm belirli bir dizine bağlı değildir:

$name = preg_replace('/_.*/', '', basename($string));