Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove everything after a space in PHP?

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
like image 325
AlphaApp Avatar asked Aug 29 '12 12:08

AlphaApp


2 Answers

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,' ');
like image 77
Codemonkey Avatar answered Nov 19 '22 07:11

Codemonkey


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

$str=substr($str, 0, strrpos($str, ' '));
like image 26
TheBlackBenzKid Avatar answered Nov 19 '22 09:11

TheBlackBenzKid