0

So I have a delimited string and I need to get the substring before the delimiter, let's take an example:

This string - DeleteMe please and some other text 

So I want to find DDeleteMe please and some other text and remove it, because all I need is This string.

1
  • Please, I am so curious: Do you only want everything before the - ? Commented Apr 10, 2010 at 0:18

4 Answers 4

2

So everything before the dash - or how does DeleteMe please and some other text qualifies to be deleted?

If so, you need no regex, you can do it with substr and strpos:

$string = "This string - DeleteMe please and some other text"; $string = trim(substr($string, 0, strpos($string, '-'))); 

You could also use explode():

$parts = explode('-', $string); $string = trim($parts[0]); 
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$fixed_string = preg_replace("(\s-.*)$", "", $your_string); 

Comments

1

You don't need regex.

$str = 'This string - DeleteMe please and some other text'; $str = substr($str, 0, strpos($str, '-') - 1); 

5 Comments

What about 'This string-DeleteMe' ? Would result in This strin.
In the example, the delimiter is ' - '. If that's not what's intended, Uffo should clarify.
No what I meant was: substr gives you the substring up to (excluding) a certain index. In your example you subtract one, which removes (in case the previous character to the index is not a space) one character too much.
Felix, I'm aware of how substr works. As I said, in the original example the delimiter is ' - ' (i.e. space dash space). I wrote my code to work with that (note the lack of trim).
Oh ok, in the comments, I could not see that you mean the dash with spaces... you should have used ' - ' ;) Ok never mind...
1
$str = preg_replace('\s*-\s*DeleteMe.*$','', $str) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.