0

我需要你的帮助。我有一个变量名$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 代码来处理这个问题。非常感谢您!

4

5 回答 5

6

使用简单的explode()函数

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

输出 :

Array ( [0] => new [1] => sample [2] => string )
于 2013-09-04T06:16:07.440 回答
3

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

$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
)
于 2013-09-04T06:22:04.680 回答
0

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

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

于 2013-09-04T06:16:43.613 回答
0
$thetextstring = "alpha bravo charlie delta echo foxtrot golf hotel india" ; 

$c=  explode(" ", $thetextstring);
print_r($c);
于 2013-09-04T06:16:53.290 回答
0
$thetextstring = "alpha bravo charlie
delta echo
foxtrot
golf hotel india" ;

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

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

print_r( $result );

首先,您应该从给定的字符串中删除所有新行,以便清楚您只有一行字符串,没有换行符/换行符。

然后 Explode 函数将从给定的字符串创建一个数组,以空格分隔。

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

于 2013-09-04T06:24:17.540 回答