use*_*108 0 php string explode
我有一个场景,用户在搜索框中输入一个字符串.如果输入的字符串到达多个单词,我会使用,
$text = "Hello World";
$pieces = explode(' ', $text);
Run Code Online (Sandbox Code Playgroud)
我将获得第一个和第二个任期
$pieces['0'] & $pieces['1'].
Run Code Online (Sandbox Code Playgroud)
但是,如果用户键入类似的内容,
$text = "Hello World";
Run Code Online (Sandbox Code Playgroud)
我应该如何获得第二个学期?
如果我var_dump的结果,我得到了
array(12) {
[0]=>
string(5) "Hello"
[1]=>
string(0) ""
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
[5]=>
string(0) ""
[6]=>
string(0) ""
[7]=>
string(0) ""
[8]=>
string(0) ""
[9]=>
string(0) ""
[10]=>
string(0) ""
[11]=>
string(5) "World"
}
Run Code Online (Sandbox Code Playgroud)
而不是explode()使用preg_split()然后使用\s+(\ s空格,+ 1或更多次)作为分隔符.像这样:
$pieces = preg_split("/\s+/", $text);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |