繁体   English   中英

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

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

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

使用简单的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
)

有关将explode与多个定界符一起使用的信息,请参见PHP explode()文档的注释中的function multiexplode

http://php.net/manual/zh/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函数将从给定的字符串中创建一个数组,并以空格分隔。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM