如何删除字符串的其余部分

0 php string

如果我有这样的字符串:

你好再见

我如何让PHP找到并删除一个特定字符和病房中的其余字符串

比如一个例子

你好再见

找到角色 -

并留下字符串

你好

Gum*_*mbo 6

使用strpos查找字符串的第一次出现的位置,然后substr只得到一切到这一位置:

$pos = strpos($str, '-');
if ($pos !== false) {  // strpos returns false if there is no needle in the haystack
    $str = substr($str, 0, $pos);
}
Run Code Online (Sandbox Code Playgroud)

如果你有PHP 5.3及更高版本,你也可以使用第三个参数设置为truestrstr函数.