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

7 Answers 7

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Recommending a deprecated function? Hmmmm
3

You could use substr and strpos:

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

Or alternatively preg_replace:

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

Comments

2

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

Comments

1

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.

Comments

1

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

Comments

1

Might be faster than preg_replace:

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

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

// result = 9453-abcafaf3ceb895d7b1636ad24c37cb9f-

Comments

0

If you want to exclude everything before the first hyphen and concatenate everything else, you could do this:

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

$str = explode('-', $str);
$count = count($str);

// So far we have the string exploded but we need to exclude
// the first element of the array and concatenate the others

$new = ''; // This variable will hold the concatenated string

for($i=1;$i<$count;++$i){
    $new.=$str[$i];
}

echo $new; // abcafaf3ceb895d7b1636ad24c37cb9f100.png?1
?>

So, basically, you loop through the elements and concatenate them as they were initially, but now we are skipping the first one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.