删除数组中每个元素的第一部分


Remove first part of each elements of an array

我有一个文本文件,如下所示:

Disable: 0
Lock: 0
Default: Value
ThisIsAnOption: foo
HereIsAnAnother: bar
AndAgain: foobar

还有更多。。。

所以现在,我这样做是为了将内容放入一个数组:

$file = './somefile.txt';
$array = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

结果:

Array ( [0] => Disable: 0 [1] => Lock: 0 [2] => Default: Value [3] => ThisIsAnOption: foo [4] => HereIsAnAnother: bar [5] => AndAgain: foobar ) 

我想做的是在一个数组中保留像零、"Value"、"foo"、"bar"answers"foobar"这样的值。所以我需要删除(带空格)"禁用:","锁定:","…"

编辑:这是我想要在末尾的数组

Array ( [0] => 0 [1] => 0 [2] => Value [3] => foo [4] => bar [5] => foobar ) 

最好的方法是什么?感谢您提前提供的帮助!

使用substr()+strpos():

<?php
// header('Content-Type: text/plain; charset=utf-8');
$array = [
    'Disable: 0',
    'Lock: 0',
    'Default: Value',
    'ThisIsAnOption: foo',
    'HereIsAnAnother: bar',
    'AndAgain: foobar'
];
foreach($array as &$value){
    $value = substr($value, strpos($value, ':') + 2);
}
print_r($array);
?>

结果:

Array
(
    [0] => 0
    [1] => 0
    [2] => Value
    [3] => foo
    [4] => bar
    [5] => foobar
)

尝试这个

 <?php
$array = [
    'Disable: 0',
    'Lock: 0',
    'Default: Value',
    'ThisIsAnOption: foo',
    'HereIsAnAnother: bar',
    'AndAgain: foobar'
];
$arr_output = array(); 
foreach($array as $val)
{
   $arr_temp = explode(":", $val);
   if(isset($arr_temp[1]))
   {
       $arr_output[] = trim($arr_temp[1]);
   }
}
echo implode(",", $arr_output);
?>

输出:

0,0,Value,foo,bar,foobar

DEMO

试试这个:

for($i = 0; $i < count($array); $i++)
{
    $temp = explode(': ', $array[$i]);
    $array[$i] = $temp[1];
}

这基本上应该在后面有一个空格的地方划分字符串,从而也删除了空格。

我已经为这个测试用例添加了$array。您将使用从文件中读取的数组。

$array = Array (
    0 => "Disable: 0",
    1 => "Lock: 0",
    2 => "Default: Value",
    3 => "ThisIsAnOption: foo",
    4 => "HereIsAnAnother: bar",
    5 => "AndAgain: foobar"
) ;
$newArray = array();
foreach ($array as $line) {
    if (strpos($line, ":")) {
        $lineArray = explode(":", $line);
        $newArray[trim($lineArray[0])] = trim($lineArray[1]);
    }
}

这给出了这样的结果:

    Disable 0
    Lock    0
    Default Value
    ThisIsAnOption  foo
    HereIsAnAnother bar
    AndAgain    foobar
    $newArray

很遗憾,您后来更改了要求