在 PHP 中用增量值替换字符串的一部分


Replacing parts of a string with incremental values in PHP

我目前在PHP中有一个字符串需要操作。

我无法修改后端代码,只能使用输出。

目前我要修改的字符串是一系列链接,格式如下:

<a href="somepage.php">some title</a><a href="somepage2.php">some other title</a><a href="somepage3.php">another title</a>

要使用我正在使用的脚本,我需要为每个链接添加一个 z-index 值,以递增的值。因此,在上面的示例中,代码最终需要如下所示:

<a href="somepage.php" style="z-index:1">some title</a><a href="somepage2.php" style="z-index:2">some other title</a><a href="somepage3.php" style="z-index:3">another title</a>

我知道如何使用str_replace替换字符串的一部分,所以如果所有链接都使用相同的 z-index 值,我可以搜索所有<a href情况并将其替换为 <a style="z-index:1" href 它会解决我的问题,但每个链接都需要不同的 z 索引值。

那么,获取包含多个链接的字符串并为每个链接添加必要的"样式"标签和 z-index 值的最有效方法是什么?

编辑

我还应该补充一点,一旦添加了 z-index 值,所有链接都需要再次连接到一个字符串中。

<?php
$src_str = '<a href="somepage.php">some title</a><a href="somepage2.php">some other title</a><a href="somepage3.php">another title</a>';
$str_list = explode('</a>', $src_str);
$result = '';
$count = 0;
foreach ($str_list as $item)
{
    if (empty($item))
    {
        continue;
    }
    list($part1, $part2) = explode('>', $item);
    $count++;
    $result .= $part1 . " style='"z-index:$count'">" . $part2 . '</a>';
}
echo $result;
// output:
// <a href="somepage.php" style="z-index:1">some title</a>
// <a href="somepage2.php" style="z-index:2">some other title</a>
// <a href="somepage3.php" style="z-index:3">another title</a>
$link = $('a[href]');
$link.each(function(k,v){
 $(v).css('z-index',some_value);
});

你应该简单地使用 jQuery 来修改你的 css。像这样:

$(a[href='your-link.php']).css("z-index", "value");