开发者

Is there a way to select the first word/combo of characters in a string, separated by spaces?

For instance, I'm trying to select the 开发者_如何转开发first word in this string:

"chocolate muffin"

So I want "chocolate", but not the " " (space) and not the "muffin" text.

I imagine I could do $separate = explode(" ",$string), and just take $separate[0], but I was wondering if there was a more efficient way to do this?

Edit: This is in PHP.


This is more efficient, although a bit less readable in my opinion:

$mystring = substr($mystring, 0, strpos($mystring, " "));

This is because with strpos the search cycle stops to the first occurrence of the charachter, then it returns the given length of the string.

With explode, the search cycle goes til the end of the string.


can also write a slight variation ...

list($res) = explode(' ',$string);


$firstword = strtok($string," ");


$first = strstr($string, ' ', true);

Please note that this will only work > PHP 5.3.

PHP strstr()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜