Sherwin Flight
Sherwin Flight

Reputation: 2363

Replacing parts of a string with incremental values in PHP

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.

Upvotes: 0

Views: 72

Answers (3)

srain
srain

Reputation: 9082

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

Upvotes: 2

uptownhr
uptownhr

Reputation: 672

$link = $('a[href]');

$link.each(function(k,v){
 $(v).css('z-index',some_value);
});

Upvotes: 1

Michael Villeneuve
Michael Villeneuve

Reputation: 4033

You should simply use jQuery to modify your css. Something like that :

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

Upvotes: 0

Related Questions