0

I currently have a string in PHP that I need to manipulate.

I cannot modify the back-end code, I can only work with the output.

Currently the string I want to modify is a series of links, in this format:

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

To work with a script I am using I need to add a z-index value to each link, in increasing values. So, in my example above, the code needs to end up looking like this:

<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>

I know how to replace part of a string using str_replace, so if all of the links were using the same z-index value I could search for all cases of <a href and replace it with <a style="z-index:1" href and it would solve my problem, but each link needs a different z-index value.

So what is the most efficient way to take a string containing multiple links, and add the necessary 'style' tag and z-index values to each one?

EDIT

I should also add that once the z-index values are added the links all need to be joined into one string again.

4

3 回答 3

2
<?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>
于 2013-10-31T04:57:00.447 回答
1
$link = $('a[href]');

$link.each(function(k,v){
 $(v).css('z-index',some_value);
});
于 2013-10-31T04:59:45.863 回答
0

您应该简单地使用 jQuery 来修改您的 css。类似的东西:

$(a[href='your-link.php']).css("z-index", "value");
于 2013-10-31T04:53:09.073 回答