Reputation: 635
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
Upvotes: 21
Views: 35633
Reputation: 47864
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.Upvotes: 1
Reputation: 15545
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;
Upvotes: 1
Reputation: 4807
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,' ');
Upvotes: 32
Reputation: 48357
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);
}
Upvotes: 1
Reputation: 4601
Try this
<?php
$x = "Laura Smith";
echo strtok($x, " "); // Laura
?>
Upvotes: 13
Reputation:
You can do also like this
$str = preg_split ('/\s/',$x);
print $str[0];
Upvotes: 0
Reputation: 11385
There is no need to use regex, simply use the explode method.
$item = explode(" ", $x);
echo $item[0]; //Laura
Upvotes: 7
Reputation: 27087
Do this, this replaces anything after the space character. Can be used for dashes too:
$str=substr($str, 0, strrpos($str, ' '));
Upvotes: 28