如何在 PHP 中的空格后删除所有内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12177788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:59:06  来源:igfitidea点击:

How do I remove everything after a space in PHP?

phpreplacepreg-replace

提问by AlphaApp

I have a database that has names and I want to use PHP replace after the space on names, data example:

我有一个有名字的数据库,我想在名字上的空格后使用 PHP 替换,数据示例:

$x="Laura Smith";
$y="John. Smith"
$z="John Doe";

I want it to return

我想要它回来

Laura
John.
John

回答by Codemonkey

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.

不过,我只是做了一个快速基准测试,因为我之前没有遇到过 strtok 方法,并且在给出的示例字符串中,strtok 比我的列表/爆炸解决方案快 25%。

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.

此外,初始字符串越长/分隔越多,性能差距就越大。给出一个 5000 个单词的块,explode 将生成一个包含 5000 个元素的数组。strtok 将只取第一个“元素”,并将其余部分作为字符串留在内存中。

So strtok wins for me.

所以 strtok 为我赢了。

$s = strtok($s,' ');

回答by TheBlackBenzKid

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

这样做,这会替换空格字符之后的任何内容。也可以用于破折号:

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

回答by Naveen Kumar

Try this

尝试这个

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

strtok

斯特托克

回答by oopbase

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

不需要使用正则表达式,只需使用explode方法即可。

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

回答by symcbean

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.

TheBlackBenzKid 提供的方法对该问题有效 - 但是,当提供不包含空格的参数时,它将返回一个空白字符串。

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

回答by Black Mamba

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

这个答案将删除第一个空格之后的所有内容,而不是最后一个空格,就像接受的答案一样。使用strpossubstr

$str = "CP hello jldjslf0";
$str = substr($str, 0, strpos( $str, ' '));
echo $str;

回答by mickmackusa

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 beforethe first occurrence of the needle string.

strstr()的第三个参数为 true,将返回第一次出现针串之前的子串。

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.

注意,如果在字符串中找不到针,strstr()将返回false

p.s.

ps

  • Because there are single-function techniques to perform this task, there is no compelling reason to use multiple-function techniquesto do the same work.
  • Because the needle is a static string (a space) there is absolutely no reason to introduce the overhead of a regex call.
  • If anyone is considering the use of 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.
  • 因为有单功能技术可以执行此任务,所以没有令人信服的理由使用多功能技术来完成相同的工作。
  • 因为指针是一个静态字符串(一个空格),所以绝对没有理由引入正则表达式调用的开销
  • 如果有人正在考虑使用explode()来生成临时数组而不是更直接的“字符串输入-字符串输出”操作,例如strtok()or strstr(),请务必声明explode()使用表示目标元素索引 + 1 的整数的第三个参数——这样,一旦分离出您要查找的子字符串,该函数将停止创建新元素。

回答by mickmackusa

You can do also like this

你也可以这样做

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

回答by Dirk McQuickly

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

$x="劳拉史密斯"; $temparray = implode(' ', $x); 回声 $temparray[0];

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

对不起,有时会混淆内爆和爆炸...