首页 > 解决方案 > 如何在 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 条记录,因此我必须删除两个数组中所有项目的空间之后的所有内容。

标签: phparraysstring

解决方案


从您的代码中,我看到您explode在错误的地方使用了函数。它应该在while loopas 字符串中,应该在那里展开以获得 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);

?>

推荐阅读