tags:

views:

34

answers:

4

So I have a random of strings and I need to parse them, 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

Best Regards,

+2  A: 

Try this:

$fixed_string = preg_replace("(\s-.*)$", "", $your_string);
Andrew Hare
+1  A: 

You don't need regex.

$str = 'This string - DeleteMe please and some other text';
$str = substr($str, 0, strpos($str, '-') - 1);
Matthew Flaschen
What about `'This string-DeleteMe'` ? Would result in `This strin`.
Felix Kling
In the example, the delimiter is ' - '. If that's not what's intended, Uffo should clarify.
Matthew Flaschen
@Matthew Flaschen: 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 Kling
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).
Matthew Flaschen
@Matthew Flaschen: Oh ok, in the comments, I could not see that you mean the dash with spaces... you should have used `' - '` ;) Ok never mind...
Felix Kling
+2  A: 

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]);
Felix Kling
+1  A: 
$str = preg_replace('\s*-\s*DeleteMe.*$','', $str)
Mark