How do I remove everything after a space in PHP?

2019-04-05 14:21发布

I have a database that has names and I want to use PHP replace after the space on names, data example:

$x="Laura Smith";
$y="John. Smith"
$z="John Doe";

I want it to return

Laura
John.
John

8条回答
2楼-- · 2019-04-05 15:14

The method provided by TheBlackBenzKid is valid for the question - however when presented with an argument which contains no spaces, it will return a blank string.

Although regexes will be more computationally expensive, they provide a lot more flexibiltiy, e.g.:

function get_first_word($str)
{
 return (preg_match('/(\S)*/', $str, $matches) ? $matches[0] : $str);
}
查看更多
Root(大扎)
3楼-- · 2019-04-05 15:15

$x="Laura Smith"; $temparray = implode(' ', $x); echo $temparray[0];

I'm sorry, sometimes mix up implode and explode...

查看更多
登录 后发表回答