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


In PHP, how to save words separated by space and lines and put words in array

我需要你的帮助。我有一个变量名$thetextstring,其中包含9个单词,用换行符和空格分隔,这些单词是我从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代码来处理这个问题。提前非常感谢!

使用简单explode()函数

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

输出:

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

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

$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
)

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

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

$thetextstring = "alpha bravo charlie delta echo foxtrot golf hotel india" ; 
$c=  explode(" ", $thetextstring);
print_r($c);
$thetextstring = "alpha bravo charlie
delta echo
foxtrot
golf hotel india" ;
$string = trim(preg_replace('/'s+/', ' ', $thetextstring));
$result =  explode(" ", $thetextstring);
print_r( $result );

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

然后,Explode函数将从由SPACE分隔的给定字符串中创建一个数组。

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