How do I remove everything after a space in PHP?

最后都变了- 提交于 2020-01-01 07:58:23

问题


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

回答1:


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

$str=substr($str, 0, strrpos($str, ' '));



回答2:


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



回答3:


Try this

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

strtok




回答4:


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

$item = explode(" ", $x);
echo $item[0]; //Laura



回答5:


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



回答6:


You can do also like this

$str = preg_split ('/\s/',$x);
print $str[0];



回答7:


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;



回答8:


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

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



来源:https://stackoverflow.com/questions/12177788/how-do-i-remove-everything-after-a-space-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!