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 14:53

There is no need to use regex, simply use the explode method.

$item = explode(" ", $x);
echo $item[0]; //Laura
查看更多
Root(大扎)
3楼-- · 2019-04-05 14:55

You can do also like this

$str = preg_split ('/\s/',$x);
print $str[0];
查看更多
不美不萌又怎样
4楼-- · 2019-04-05 15:05

Do this, this replaces anything after the space character. Can be used for dashes too:

$str=substr($str, 0, strrpos($str, ' '));
查看更多
冷血范
5楼-- · 2019-04-05 15:06

This answer will remove everything after the first space and not the last as in case of accepted answer.Using strpos and substr

$str = "CP hello jldjslf0";
$str = substr($str, 0, strpos( $str, ' '));
echo $str;
查看更多
地球回转人心会变
6楼-- · 2019-04-05 15:11

Just to add it into the mix, I recently learnt this technique:

list($s) = explode(' ',$s);

I just did a quick benchmark though, because I've not come across the strtok method before, and strtok is 25% quicker than my list/explode solution, on the example strings given.

Also, the longer/more delimited the initial string, the bigger the performance gap becomes. Give a block of 5000 words, and explode will make an array of 5000 elements. strtok will just take the first "element" and leave the rest in memory as a string.

So strtok wins for me.

$s = strtok($s,' ');
查看更多
祖国的老花朵
7楼-- · 2019-04-05 15:12

Try this

<?php
$x = "Laura Smith";
echo strtok($x, " "); // Laura
?>

strtok

查看更多
登录 后发表回答