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
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
I hope these patterns will help you =]
Explode or regexp are an overkill, try this:
$str = substr($str, 0, strpos($str,'-'));
or the strtok version in one of the answers here.
You could use
strtok
:You can also use.
The third parameter
true
tells the function to return everything before first occurrence of the second parameter.Source on strstr() from php.net
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:
No need for regex. You can use
explode
:or
substr
andstrpos
: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:So you see, there is no regular expression needed ;)