Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove anything in a string after "-"?

Tags:

This is the example of my string.

$x = "John Chio - Guy"; $y = "Kelly Chua - Woman"; 

I need the pattern for the reg replace.

$pattern = ?? $x = preg_replace($pattern, '', $x);  

Thanks

like image 452
Mister Gan Avatar asked Jan 16 '11 11:01

Mister Gan


People also ask

How do you delete everything after string?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you delete certain elements from a string?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do you delete everything after a string in Python?

To remove everything after a character in a string: Use the str. split() method to split the string on the separator. Access the list element at index 0 to get everything before the separator.


2 Answers

No need for regex. You can use explode:

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

or substr and strpos:

$str = substr($str, 0, strpos($str, '-')); 

Maybe in combination with trim to remove leading and trailing whitespaces.

Update: As @Mark points out this will fail if the part you want to get contains a -. It all depends on your possible input.

So assuming you want to remove everything after the last dash, you can use strrpos, which finds the last occurrence of a substring:

$str = substr($str, 0, strrpos($str, '-')); 

So you see, there is no regular expression needed ;)

like image 186
Felix Kling Avatar answered Sep 20 '22 17:09

Felix Kling


To remove everything after the first hyphen you can use this regular expression in your code:

"/-.*$/" 

To remove everything after the last hyphen you can use this regular expression:

"/-[^-]*$/" 

http://ideone.com/gbLA9

You can also combine this with trimming whitespace from the end of the result:

"/\s*-[^-]*$/" 
like image 34
Mark Byers Avatar answered Sep 17 '22 17:09

Mark Byers