我有一个文本文件,其中包含数字如下:
12345678901234567890
123456789012345678901
123456789012345678902
1234567890123456789012
1234567890123456789023
12345678901234567890123
12345678901234567890234
我写了一个脚本来逐行读取这个文件。我想计算行中的字符,而不仅仅是字节,并且只选择包含21或22个字符的行。
使用下面的脚本有效。当我说23时,不要问我为什么它读了21个字符。我认为它与文件编码有关,因为strlen
只给我字节。
选择长度为21或22个字符的行后,我需要拆分该行。如果它是21,它应该变成两个字符串(一个15个字符的字符串和一个6个字符的字符串), 如果是22个字符,则应分成16个字符的字符串和6个字符的字符串。
我尝试在数组中创建它,但数组显示如下:
Array ( [0] => 123456789012345 [1] => 678901 ) Array ( [0] => 123456789012345 [1] => 678903 )
我希望它显示为这样:
123456789012345=678901
123456789012345=678903
知道我怎么能从数组中回应吗?
$filename = "file.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while (!feof($fp)){
$line = fgets($fp);
$str = strlen($line);
if($str == 23){
$str1=str_split($line, 15);
print_r($str1);
foreach ($str1 as $value)
{
echo $value . "=" ;
}
}
if($str == 24){
$str1=str_split($line, 16);
foreach ($str1 as $value)
{
echo $value . "=" ;
}
}
}
答案 0 :(得分:2)
只是一些指示:
$filename = "file.txt";
$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === FALSE) {
die "Couldn't open $filename";
}
foreach ($lines as $line)
{
$length = strlen($line);
if ($length < 21 || $length > 22) {
continue;
}
$start = 15;
if ($length === 22) {
$start = 16;
}
echo substr($line, 0, $start), '=', substr($line, $start), "\n";
}
即使用file
和substr
。在PHP中,一个字符是一个字节。
另一个例子:
$filename = "file.txt";
$lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === FALSE) {
die "Couldn't open $filename";
}
foreach ($lines as $line)
{
$start = strlen($line) - 6;
if ($start === 15 || $start === 16)
{
echo substr_replace($line, '=', $start, 0), "\n";
}
}
此示例使用substr_replace
并直接进行$start
计算。