views:

47

answers:

5

Hi!

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.

I've got a string variable called $stuff

if $stuff = 145_timestamp i want to clear the _ and the chars after it. so i want to $stuff be 145 only. Thanks.

+2  A: 

try explode, which will split a string into an array based on a delimiter. If you use _ as the delimiter, then you can pick the first value from the array using current:

$number = current(explode("_", $stuff));
Marius
This is the most inefficient way to do it - explode goes to all the effort of constructing an array of values, but these are never used. It's 10 times slower than murugaperumal's int cast suggestion.
Paul Dixon
Premature optimization and so on... :p
Marius
+1  A: 
$string = preg_replace("/_[^_]+$/",'',$string);
Piskvor
What if there is more than one `_`?
Gumbo
should be "/_.*/", but +1 - regexp is the way to go.
stereofrog
+3  A: 
$stuff = "145_timestamp";
$stuff=(int)$stuff;
print $stuff;
muruga
note: if $stuff = "020_timestamp", it will become 20. This may or may not be the same thing as 020.
Piskvor
A: 

intval fetches the integer value of strings. Or you could use a regular expression or explode:

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

I ran some benchmarks over the various methods suggested here, adding a few suggestions of my own - these are the timings for 100000 iterations of each method

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

The int cast method wins by a mile, but as noted, you will strip off leading zeros. Intval is a slower method of achieving the same result.

A fast method to get the string with a leading zero is to use strtok($str, '_');

$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);
Paul Dixon
+1 for testing. The reason why int cast is faster is that it's implemented as a single opcode in ZE and doesn't involve a function call.
stereofrog
@Paul Dixon: good stuff. What about doing the replace/cast in SQL?
middus