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
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,' ');
Do this, this replaces anything after the space character. Can be used for dashes too:
$str=substr($str, 0, strrpos($str, ' '));
strrpos()
, the last whitespace is searched for and you might end up with names like "Hello Nice" for strings like "Hello Nice World". The second point is that it won't return anything when there is no whitespace in the name at all. While this behavior might be wanted, it might also cause annoyance.
There is no need to use regex, simply use the explode method.
$item = explode(" ", $x);
echo $item[0]; //Laura
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);
}
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;
There is an unmentioned function call that I consistently use for this exact task.
strstr() with a third parameter of true, will return the substring before the first occurrence of the needle string.
Code: (Demo)
$array = [
'x' => 'Laura Smith',
'y' => 'John. Smith',
'z' => 'John Doe'
];
foreach ($array as $key => $value) {
$array[$key] = strstr($value, ' ', true);
}
var_export($array);
Output:
array (
'x' => 'Laura',
'y' => 'John.',
'z' => 'John',
)
Note, if the needle is not found in the string, strstr()
will return false
.
p.s.
explode()
to produce a temporary array instead of a more direct "string in - string out" operation such as strtok()
or strstr()
, be sure to declare the third parameter of explode()
using the integer that represents your targeted element's index + 1 -- this way the function will stop making new elements as soon as it has isolated the substring that you seek.