views:

113

answers:

6

Which string function can I use to strip everything after - ? The string is not predefined so rtrim() does not work.

9453-abcafaf3ceb895d7b1636ad24c37cb9f-100.png?1

+4  A: 

Use the split explode function and the "-" character as the delimiter. It will return an array of strings. If you only care about information before the first dash, just use the zeroth index of the returned array.

edit:
Sorry. After living in the python world for several months, split was the first thing that came to mind. explode is the correct function.

edit 2:
strip, lstrip, and rstrip are meant to be used for trimming whitespace off the end(s) of a string.

advait
Recommending a deprecated function? Hmmmm
quantumSoup
@patrick, i compared this solution to evil3's, and evil3's is clearly superior. explode is too expensive for what you actually need, clearly substr/strpos is the most optimized solution. i tested a 60 character string with sporadic hyphens. `~$ php test.php` `Explode ran 100000 times in 925ms` `substr/strpos ran 100000 times in 141ms`
+1  A: 

It depends on which dash? I would recommend using explode and just getting the array element for the string portion you want. Check it out: http://php.net/explode

Again, this will be very dependent on the amount of dashes in the string and may require additional logic.

Jason McCreary
+6  A: 

You could use substr and strpos:

$id = substr($path, 0, strpos($path, '-'));

Or alternatively preg_replace:

$id = preg_replace('/(.*?)-.*/', '\1', $path);
igorw
+1  A: 

I believe he wants to get rid of the rightmost -. In this case you can use regex:

$s = '9453-abcafaf3ceb895d7b1636ad24c37cb9f-100.png?1';
$str = preg_replace('!-[^-]*$!', '', $s);

echo $str; // outputs 9453-abcafaf3ceb895d7b1636ad24c37cb9f
quantumSoup
+1  A: 

If you know that the left portion of the string is always numeric, you can use PHP's auto type conversion and just add it to zero. (assuming you mean the first hyphen)

Try this:

print 0 + '9453-abcafaf3ceb895d7b1636ad24c37cb9f-100.png?1'; //outputs 9453

Rimian
+1  A: 

Might be faster than preg_replace:

$str = '9453-abcafaf3ceb895d7b1636ad24c37cb9f-100.png?1';

$str = explode('-', $str);
array_pop($str);
$str = implode('-', $str) . '-';

// result = 9453-abcafaf3ceb895d7b1636ad24c37cb9f-
Jhong