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
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
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.
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.
You could use substr and strpos:
$id = substr($path, 0, strpos($path, '-'));
Or alternatively preg_replace:
$id = preg_replace('/(.*?)-.*/', '\1', $path);
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
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
Might be faster than preg_replace:
$str = '9453-abcafaf3ceb895d7b1636ad24c37cb9f-100.png?1';
$str = explode('-', $str);
array_pop($str);
$str = implode('-', $str) . '-';
// result = 9453-abcafaf3ceb895d7b1636ad24c37cb9f-