3

几个小时以来,我一直在尝试将 foreach 与 2 个数组一起使用。这是我的代码:

function displayTXTList($fileName) {

    if (file_exists($fileName)) {
        $contents = file($fileName);
        $string   = implode($contents);
        preg_match_all('#\[\[(\w+)\]\]#u', $string, $name);
        preg_match_all('/style=(\'|\")([ -0-9a-zA-Z:]*[ 0-9a-zA-Z;]*)*(\'|\")/', $string, $name2);
        $i = 0;
        foreach ($name[1] as $index => $value) {
            echo '<br/>' . $value, $name2[$index];
        }
    }
}

displayTXTList('smiley2.txt');

这是我得到的:

sadArray
cryingArray
sunArray
cloudArray
raining
coffee
cute_happy
snowman
sparkle
heart
lightning
sorry
so_sorry
etc...

但我想要这个:

sadstyle='background-position: -0px -0px;'
cryingstyle='background-position: -16px -0px;'
sunstyle='background-position: -32px -0px;'
etc...

实际的txt文件是这样的:

[[sad]]<span class='smiley' style='background-position: -0px -0px;'></span>
[[crying]]<span class='smiley' style='background-position: -16px -0px;'></span>
[[sun]]<span class='smiley' style='background-position: -32px -0px;'></span>
[[cloud]]<span class='smiley' style='background-position: -48px -0px;'></span>
[[raining]]<span class='smiley' style='background-position: -64px -0px;'></span>
etc...

我怎么能做到这一点?我是新来的,所以请不要记下:/

4

1 回答 1

2

您正在将数组输出为字符串(因此Array在输出中,如果您将数组转换为字符串(例如使用echo),PHP 会将其转换为"Array")。而是访问数组内的匹配项(我假设组 0 为$name2,请检查):

echo '<br/>' .$value , $name2[0][$index];
                             ^^^--- was missing

function displayTXTList($fileName) {

    if (!file_exists($fileName)) {
        return;
    }

    $string = file_get_contents($fileName);

    $names  = preg_match_all('#\[\[(\w+)\]\]#u', $string, $matches) ? $matches[1] : array();
    $styles = preg_match_all(
        '/style=(\'|\")([ -0-9a-zA-Z:]*[ 0-9a-zA-Z;]*)*(\'|\")/', $string, $matches
    ) ? $matches[0] : array();

    foreach ($names as $index => $name) {
        $style = $styles[$index];
        echo '<br/>', $name, $style;
    }
}

displayTXTList('smiley2.txt');
于 2012-12-30T16:41:06.903 回答