繁体   English   中英

用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-index值。

那么,获取包含多个链接的字符串并向每个链接添加必要的'style'标签和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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM