在PHP中,如何保存由空格和行分隔的单词并将单词放在数组中

时间:2013-09-04 06:12:47

标签: php arrays string tokenize

我需要你的帮助。我有一个变量名 $ thetextstring ,其中包含9个单词,用LINE BREAKS和SPACES分隔,我从html表单中提取。

$thetextstring = "alpha bravo charlie
delta echo
foxtrot
golf hotel india" ;

如何标记php字符串$ thetextstring以删除行和空格并将9个单词放入数组中

$thetextarray[0] = "alpha";
$thetextarray[1] = "bravo";
$thetextarray[2] = "charlie";
$thetextarray[3] = "delta";
$thetextarray[4] = "echo";
$thetextarray[5] = "foxtrot";
$thetextarray[6] = "golf";
$thetextarray[7] = "hotel";
$thetextarray[8] = "india";

我需要php代码来处理这个问题。非常感谢你提前!

5 个答案:

答案 0 :(得分:6)

使用简单的explode()函数

$str="new sample string";
$str=preg_replace("/\s+/", " ", $str);
$arr=explode(" ",$str);
print_r($arr);

输出:

Array ( [0] => new [1] => sample [2] => string )

答案 1 :(得分:4)

这是你想要的,我删除了所有额外的新行和空格。

$thetextstring = "alpha bravo charlie
delta echo
foxtrot
golf hotel india" ;
$thetextstring = preg_replace("#[\s]+#", " ", $thetextstring);
$words = explode(" ", $thetextstring);
print_r($words);

(
    [0] => alpha
    [1] => bravo
    [2] => charlie
    [3] => delta
    [4] => echo
    [5] => foxtrot
    [6] => golf
    [7] => hotel
    [8] => india
)

答案 2 :(得分:0)

请参阅PHP multiexplode文档注释中的函数explode(),以了解如何使用具有多个分隔符的explode。

http://php.net/manual/en/function.explode.php#111307

答案 3 :(得分:0)

$thetextstring = "alpha bravo charlie delta echo foxtrot golf hotel india" ; 

$c=  explode(" ", $thetextstring);
print_r($c);

答案 4 :(得分:0)

$thetextstring = "alpha bravo charlie
delta echo
foxtrot
golf hotel india" ;

$string = trim(preg_replace('/\s+/', ' ', $thetextstring));

$result =  explode(" ", $thetextstring);

print_r( $result );

首先,你应该从给定的字符串中删除所有新行,这样就可以清楚地知道你只有一行字符串而没有新行字符/符号。

然后,爆炸功能将从由SPACE分隔的给定字符串创建一个数组。

last您可以打印结果,将每个单词看作数组中的单个实体。