php 在php中第一次出现字符之前返回字符串的部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3766301/
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
Return the portion of a string before the first occurrence of a character in php
提问by Travis
In PHP, what is the simplest way to return the portion of a string before the first occurrence of a specific character?
在 PHP 中,在特定字符第一次出现之前返回字符串部分的最简单方法是什么?
For example, if I have a string...
例如,如果我有一个字符串...
"The quick brown foxed jumped over the etc etc."
“敏捷的棕色狐狸跳过等等等等。”
...and I am filtering for a space character (" "), the function would return "The"
...我正在过滤一个空格字符(“”),该函数将返回“The”
Thanks!
谢谢!
回答by user187291
回答by Jacob Relkin
You coulddo this:
你可以这样做:
$string = 'The quick brown fox jumped over the lazy dog';
$substring = substr($string, 0, strpos($string, ' '));
But I like this better:
但我喜欢这样更好:
list($firstWord) = explode(' ', $string);
回答by Tilman K?ster
strstr()
Find the first occurrence of a string. Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.Third param: If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).
strstr()
查找第一次出现的字符串。返回 haystack 字符串的一部分,从针头的第一次出现开始到 haystack 结束。第三个参数:如果为 TRUE,则 strstr() 返回第一次出现针之前的部分干草堆(不包括针)。
$haystack = 'The quick brown foxed jumped over the etc etc.';
$needle = ' ';
echo strstr($haystack, $needle, true);
Prints The
.
打印The
。
回答by tjk
How about this:
这个怎么样:
$string = "The quick brown fox jumped over the etc etc.";
$splitter = " ";
$pieces = explode($splitter, $string);
echo $pieces[0];
回答by Hebe
To sum up there're 4 ways
总结起来有4种方式
strstr($str,' ',true);
strtok($str,' ');
explode(' ', $str)[0]; //slowest
substr($str, 0, strpos($str, ' '));
The difference is that if no delimiter found:
不同之处在于,如果没有找到分隔符:
strstr
returns false
strstr
返回假
strtok
explode
returns whole string
strtok
explode
返回整个字符串
substr
returns empty string
substr
返回空字符串
if unexpected troubles with multibyte appear then this example
如果出现意外的多字节问题,那么这个例子
$str = mb_strstr($str, 'и', true) ?: $str;