php 从php中的字符串中获取前两个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13263523/
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 05:04:12  来源:igfitidea点击:

Getting first two words from string in php

phpstring

提问by fawad

I have string like:

我有这样的字符串:

$message="AB 1234 Hello, how are you?

I want to get like this:

我想变成这样:

$message[0] = AB
$message[1] = 1234
$message[2] = Hello, how are you?

Please don't suggest substr function because length of first two words may vary but they will have spaces in between. Any other suggestion?

请不要建议 substr 函数,因为前两个单词的长度可能会有所不同,但它们之间会有空格。还有什么建议吗?

回答by Phil

Use explode()with a limit, eg

explode()有限制地使用,例如

$message = explode(' ', $message, 3);

If you need more flexibility around the word delimiter, you can do something similar with preg_split()

如果您需要更灵活地使用单词分隔符,您可以执行类似的操作 preg_split()

$message = preg_split('/[\s,]+/', $message, 3)

Demo - http://codepad.org/1gLJEFIa

演示 - http://codepad.org/1gLJEFIA

回答by Bhavik Patel

you can use the following function.

您可以使用以下功能。

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

output:
//piece1
//piece2

More information: http://php.net/manual/en/function.explode.php

更多信息:http: //php.net/manual/en/function.explode.php

回答by alex

If wordsare simply the first two chunks delimited by sequential whitespace, you could do...

如果单词只是由连续空格分隔的前两个块,你可以这样做......

$words = preg_split("/\s+/", $str);

If you want the first two, you could use preg_split()'s limit argument (thanks Phil).

如果你想要前两个,你可以使用preg_split()'s limit 参数(感谢Phil)。

回答by Anthony Sterling

Check out sscanf, be sure to read the user submitted comments though too. You can find a better description of the formats allowed at http://www.cplusplus.com/reference/clibrary/cstdio/scanf/.

查看sscanf,但一定要阅读用户提交的评论。您可以在http://www.cplusplus.com/reference/clibrary/cstdio/scanf/找到对所允许格式的更好描述。

<?php
$string = 'AB 1234 Hello, how are you?';
$array = sscanf($string, '%s %d %[^$]');
var_dump($array);
/*
    array(3) {
      [0]=>
      string(2) "AB"
      [1]=>
      int(1234)
      [2]=>
      string(19) "Hello, how are you?"
    }
*/