Mcod Posted September 4, 2011 Share Posted September 4, 2011 Hello, I am currently having an issue with removing a string from within a string. The strings I deal with are like the examples below: This is - a test - because tests are fun - abc This is - a test because tests are fun - def This is a test - because tests are fun - ghi The good news is that the end is always the same - basically a space, a minus and a space followed by random chars. So technically I would need to remove everything from a string starting at the last space minus space incl the space, minus, space. The result for the examples above would then be: This is - a test - because tests are fun This is - a test because tests are fun This is a test - because tests are fun Would be great if somebody could help me with this (to me) impossible task. Thanks Quote Link to comment Share on other sites More sharing options...
silkfire Posted September 4, 2011 Share Posted September 4, 2011 Oh that's easy: $string = 'This is - a test - because tests are fun - abc'; $string = preg_replace('#^(.*) - .*$#', '$1', $string); Quote Link to comment Share on other sites More sharing options...
Mcod Posted September 4, 2011 Author Share Posted September 4, 2011 Thank you very much - that did the job more than well Quote Link to comment Share on other sites More sharing options...
silkfire Posted September 4, 2011 Share Posted September 4, 2011 Anytime Mcod. Come here again and we'll help you out. Quote Link to comment Share on other sites More sharing options...
Mcod Posted September 4, 2011 Author Share Posted September 4, 2011 You can be sure that i will Again, thanks a lot - didn't expect an answer that quickly! Just wow Quote Link to comment Share on other sites More sharing options...
silkfire Posted September 4, 2011 Share Posted September 4, 2011 If you want to remove 6 characters from the end the approach would be different. Is it always 3 random chars? Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted September 4, 2011 Share Posted September 4, 2011 If it's always the characters including and after the last hyphen that need to be removed, you don't even need to use a regex pattern for it. $string = trim(substr( $string, 0, strrpos($string, '-') )); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.