0

I want to get the part of the string before the last occurance of "-",

for example,

$string1 = 'a-b-c-de-f-gfgh';

I want to get this part returned: a-b-c-de-f. Of course, I don't know the length of the last part.

What is the easy way to do it?

Thank you

1
  • So many ways, what have you tried? Commented May 11, 2012 at 22:13

5 Answers 5

7
echo substr ($string1, 0, strrpos ($string1, '-'));

strrpos() finds the last occurrence of a substring, - in this case, and substr() splits the original string from the 0th character until the nth character as defined by strrpos()

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

Comments

1

Use strrpos() to get position of last "-" and substr() it:

echo substr($string1, 0, strrpos($string1, "-"));

Comments

1

get the last occurrence of - using $x = strrpos($string1,'-'); then use substr() to return the decired string from 0 to $x

 echo substr ($string1, 0, $x);

Comments

0

You could remove that last part:

$string = preg_replace("|-[^-]+$|", "", $string);

Comments

0

As an alternative to the other posters:

preg_match('/(.*)-[^-]+/', 'a-b-c-de-f-gfgh', $result);

Result:

Array
(
    [0] => a-b-c-de-f-gfgh-a
    [1] => a-b-c-de-f-gfgh
)

Though I like Jeroens solution more.

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.