我有用户在搜索框中输入字符串的场景。如果输入的字符串超过一个单词,则使用
将其分解。$text = "Hello World";
$pieces = explode(' ', $text);
我将得到第一项和第二项通过
$pieces['0'] & $pieces['1'].
但是,如果用户输入像
这样的东西$text = "Hello World";
我怎么得到第二项?
如果我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"
}
用preg_split()
代替explode()
,然后用's+
('s空格,+ 1次或多次)作为分隔符。这样的:
$pieces = preg_split("/'s+/", $text);
Rizier123的答案是足够有效的,但如果你想避免使用preg_split
使用正则表达式检查,你可以得到你的数组与空字符串,只是从它删除所有空元素,像这样:
$text = "Hello World";
$pieces = array_filter(explode(' ', $text));
用一个空格代替多个空格
$output = preg_replace('!'s+!', ' ', $text);
然后分割文本
$pieces = explode(' ', $output);
Try:
<?php
$text = "Hello World";
// BONUS: remove whitespace from beginning and end of string
$text = trim($text);
// replace all whitespace with single space
$text = preg_replace('!'s+!', ' ', $text);
$pieces = explode(' ', $text);
?>