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
Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .
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.
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.
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 ;)
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*-[^-]*$/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With