How to remove anything in a string after “-”?

2020-02-16 17:15发布

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

标签: php regex
7条回答
狗以群分
2楼-- · 2020-02-16 17:41

I hope these patterns will help you =]

$pattern1='/.+(?=\s-)/'       //This will match the string before the " -";
$pattern2='/(?<=\s-\s).+/'    //This will match the string after the "- ";
查看更多
倾城 Initia
3楼-- · 2020-02-16 17:47

Explode or regexp are an overkill, try this:

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

or the strtok version in one of the answers here.

查看更多
▲ chillily
4楼-- · 2020-02-16 17:50

You could use strtok:

$x = strtok($x, '-');
查看更多
在下西门庆
5楼-- · 2020-02-16 17:51

You can also use.

strstr( "John Chio - Guy", "-", true ) . '-';

The third parameter true tells the function to return everything before first occurrence of the second parameter.

Source on strstr() from php.net

查看更多
时光不老,我们不散
6楼-- · 2020-02-16 18:02

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*-[^-]*$/"
查看更多
我命由我不由天
7楼-- · 2020-02-16 18:05

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 ;)

查看更多
登录 后发表回答