php - 如何在 PHP 中的每个数组对象中删除空格后的所有内容?
问题描述
我有两个包含每个数组对象的字母和数字的数组。例如:“马修 20897”。我想从每个数组对象中删除数字,以便我可以比较两个数组并查看它们是否有任何共同的单词/名称。我尝试做一个爆炸来摆脱空间,但我得到一个错误,说爆炸()期望参数 2 是一个字符串。
以下是我到目前为止的代码:
<?php
//simple read file and print
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$word = fgets($connectionBoy); //read a record
$word = rtrim($word); //gets rid of end of record char
$boy[] = $word;
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$word2 = fgets($connectionGirl); //read a record
$word2 = rtrim($word2); //gets rid of end of record char
$girl[] = $word2;
}
fclose($connectionBoy);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$itemBoy = explode(" ",$boy);
$itemGirl = explode(" ",$girl);
$result =array_intersect($itemBoy,$itemGirl);
print_r($result);
此外,两个数组都存储了 1000 条记录,因此我必须删除两个数组中所有项目的空间之后的所有内容。
解决方案
从您的代码中,我看到您explode
在错误的地方使用了函数。它应该在while loop
as 字符串中,应该在那里展开以获得 name 的第一个单词。我已经更新了你的代码。
<?php
$boy = array();
$girl = array();
$connectionBoy = fopen("boynames.txt", "r") or die("Can't open boynames.txt file.");
$connectionGirl = fopen("girlnames.txt", "r") or die("Can't open girlnames.txt file.");
while(! feof($connectionBoy)){ //while it is not the end of the file
$line = fgets($connectionBoy); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$boy[] = $parts[0];
}
while(! feof($connectionGirl)){ //while it is not the end of the file
$line = fgets($connectionGirl); //read a record
$line = trim($line); //gets rid of end of record char
$parts = explode(" ",$line);
$girl[] = $parts[0];
}
fclose($connectionBoy);
fclose($connectionGirl);
echo "Number of names in the boynames file are ".sizeof($boy)."<br>";
echo "Number of names in the boynames file are ".sizeof($girl);
$result =array_intersect($boy,$girl);
print_r($result);
?>
推荐阅读
- python - Django如何按相关模型过滤和排序查询集
- ios - Firebase Cloud Messaging to Android 工作,但 iOS 失败。如何为 iOS 构建有效负载?
- angular - RadioButtonGroup-formControlName 不适用于反应式表单
- java - 如何创建一个接受一定数量的密码字符的 GUI?
- codenameone - bouncycastle 库和模态对话框的垫块损坏,无法在最小化的应用程序上显示
- typescript - 列出类的私有属性名称
- php - 带有检查是否已经存在的 Symfony 表单类型(LocationType)(尝试过 EventListener、Transformer....)
- java - TextView setContentDescription 不起作用
- postgresql - Symfony 上的 Doctrine 迁移以更新多个 Schema 中的表
- php - 我想检查用户名是否在注册页面中可用