PHP:在多个字符串

时间:2015-04-29 18:51:49

标签: php

我目前正在使用rtrim()从字符串中删除尾随换行符。有没有更有效的方法来运行以下命令?

$a = rtrim($a);
$b = rtrim($b);
...
$z = rtrim($z);

(注意,$a .. $z只是占位符,它们不是真正的变量名称)

这些变量是通过以下功能

创建的
foreach ($xml->xpath('//hardware') as $hwprofile) {
        $machine .= $hwprofile->machine . "\n";
        $count .= $hwprofile->ProcessorInfo->count . "\n";
        $speed .= $hwprofile->ProcessorInfo->speed . "\n";
        $type .= $hwprofile->ProcessorInfo->type . "\n";
        $arch .= $hwprofile->ProcessorInfo->architecture . "\n";
}

我想修剪这些变量,因为它们都有尾随换行符

3 个答案:

答案 0 :(得分:6)

这应该适合你:

只需使用变量名称填充数组$items即可。然后它循环遍历所有变量并使用variable variables和rtim它们。

$items = range("a", "z"); //your variable names e.g. $items = ["machine", "count"]

foreach($items as $item) {
    $$item = rtrim($$item);
}

你也可以使用另一种变体,因为你说你需要在每一行之间有一条新线,期望最后一行,只需创建一个这样的数组:

foreach ($xml->xpath('//hardware') as $hwprofile) {
        $machine[] = $hwprofile->machine;
        $count[] = $hwprofile->ProcessorInfo->count;
        $speed[] = $hwprofile->ProcessorInfo->speed;
        $type[] = $hwprofile->ProcessorInfo->type;
        $arch[] = $hwprofile->ProcessorInfo->architecture;
}

如果您现在需要它,请使用:

implode(PHP_EOL, $machine);

答案 1 :(得分:0)

所以我认为更清晰的解决方案是,不是在每次迭代中附加字符串,然后修剪,而是可以执行以下操作:

当前字符串并且每次附加的变量都成为数组。 对于每次迭代,将值附加到适当的数组,不带新行字符。

当您需要使用值调用implode(" \ n",$ array)时,它会使用换行符或您选择的其他任何分隔符加入值

答案 2 :(得分:0)

删除这些尾随换行符的最有效方法是在生成它的函数(foreach循环)中执行此操作。

创建后处理它们会使用更多资源(内存分配,解释,更改变量值等)。

如果您想使处理更容易编写,那么其他答案应该没问题。

不要使用更清晰/更容易编写代码来混淆效率(以更好/更便宜的方式处理某些功能)。< / p>