Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中,如何保存由空格和行分隔的单词,并将单词放入数组中_Php_Arrays_String_Tokenize - Fatal编程技术网

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

在PHP中,如何保存由空格和行分隔的单词,并将单词放入数组中,php,arrays,string,tokenize,Php,Arrays,String,Tokenize,我需要你的帮助。我有一个变量名$thetextstring,它包含9个用换行符和空格分隔的单词,这些单词是我从html表单中获取的 $thetextstring = "alpha bravo charlie delta echo foxtrot golf hotel india" ; 如何标记php字符串$thetextstring以删除行和空格,并将9个单词放入这样的数组中 $thetextarray[0] = "alpha"; $thetextarray[1] = "bravo"; $th

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

使用简单函数

输出:

Array ( [0] => new [1] => sample [2] => string )
请参阅PHP explode文档注释中的函数multiexplode,了解如何将explode与多个分隔符一起使用


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

$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函数;这不是正确的答案,您测试并查看了输出结果了吗?不,在我在phpfiddle.org上运行代码之前,您需要删除额外的空格和新行,这是输出数组[0]=>new[1]=>sample@mostafakhansa,您确定吗?
$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" ;
$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
)
$thetextstring = "alpha bravo charlie
delta echo
foxtrot
golf hotel india" ;

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

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

print_r( $result );