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
Getting first two words from string in php
提问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
回答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
回答by alex
回答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?"
}
*/

