php dize manipülasyon ("_" ve zaman damgası temizleyin)

3 Cevap php

I cant find the way how to strip the useless section of my string (read from SQL) I've tried the strreplace and truncate but those was not good at all.

Ben $ şeyler adında bir string değişken var

$stuff = 145_timestamp i ondan sonra _ ve karakter silmek istiyorsanız. öylesine i $stuff be 145 sadece istiyorum. Teşekkürler.

3 Cevap

sınırlayıcı esas alınarak bir diziye bir dize bölmek, hangi explode deneyin. Eğer sınırlayıcı olarak _ kullanırsanız, o zaman kullanarak dizinin ilk değerini almak current yapabilirsiniz:

$number = current(explode("_", $stuff));

Ben kendi bir kaç öneri ekleyerek, burada önerilen çeşitli yöntemler üzerinde bazı kriterler koştu - bu her yöntemin 100000 tekrarlamalar için zamanlamaları vardır

int cast     :  79.45ms
intval       : 394.39ms
strtok       : 428.85ms
preg_replace : 604.68ms
substr       : 719.92ms
explode      : 821.99ms

Int döküm yöntemi, bir mil tarafından kazanır, ama belirtildiği gibi, sen öndeki sıfırları kapalı şerit olacak. Intval, aynı sonucun elde edilmesi için daha düşük bir yöntemdir.

with önde gelen sıfır dize almak için hızlı bir yöntem Strtok ($ str, '_') kullanmak için;

$str="154_timestamp";
$c=100000;

$s=microtime(true);
for ($x=0; $x<$c; $x++)
    $n=(int)$str;
printf("int cast : %0.2fms\n", (microtime(true)-$s)*1000);

$s=microtime(true);
for ($x=0; $x<$c; $x++)
    $n = current(explode("_", $str));
printf("explode : %0.2fms\n", (microtime(true)-$s)*1000);

$s=microtime(true);
for ($x=0; $x<$c; $x++)
    $n = substr($str, 0, strpos($str, '_'));
printf("substr : %0.2fms\n", (microtime(true)-$s)*1000);

$s=microtime(true);
for ($x=0; $x<$c; $x++)
    $n = strtok($str, '_');
printf("strtok : %0.2fms\n", (microtime(true)-$s)*1000);

$s=microtime(true);
for ($x=0; $x<$c; $x++)
    $n = intval($str);
printf("intval : %0.2fms\n", (microtime(true)-$s)*1000);

$s=microtime(true);
for ($x=0; $x<$c; $x++)
     $n = preg_replace("/_[^_]+$/",'',$str);
printf("preg_replace : %0.2fms\n", (microtime(true)-$s)*1000);

intval dizeleri tamsayı değeri getirir. Yoksa normal bir ifade kullanın veya patlayabilir:

$int = preg_replace('/^(\d+)/', '$1', $string);
$int = explode('_',  $string)[0];