0

Is it possible with php to make a string of, say, <a>-elements comma-separated?

The situation is that a foreach loop appends a number of <a> links to an $output variable one after the other:

$output = '<a>link</a><a>link</a><a>link</a><a>link</a><a>link</a>';

Is it afterwards possible in php to comma-separate them and achieve the below string?

$output = '<a>link</a>,<a>link</a>,<a>link</a>,<a>link</a>,<a>link</a>';

Or is the most efficient way to add the comma inside the foreach loop (and then to use an if-command to skip the last one, or something like that, since that will add one comma too many)?

Steeven
  • 4,057
  • 8
  • 38
  • 68

6 Answers6

2
$output = preg_replace("/a><a","/a>,<a",$output);
Gbenankpon
  • 167
  • 2
  • 6
1

A simple replace might do the job for you:

preg_replace('/a><a/','a>,<a',$s);
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
1

In your foreach loop, rather than concatenating the item on to the end of an existing string, push them to an array:

$parts = array();

foreach($list as $item){
    $parts[] = "<a>$item</a>";
}

Then, you can simply join (implode) the array elements together to get your desired result:

$output = implode(',', $parts);
George
  • 36,413
  • 9
  • 66
  • 103
1

there are 2 solutions

solution 1 (with str_replace()):

$output = '<a>link</a><a>link</a><a>link</a><a>link</a><a>link</a>';
echo str_replace("</a>","</a>,", $output);

Solution 2 (with explode and implode method):

$exploded = explode("</a>",$output);
echo implode("</a>,", $exploded);

Side Note: you can remove the last `"," by using rtrim() method

devpro
  • 16,184
  • 3
  • 27
  • 38
1

You can replace </a> with </a>,, then trim the last `,', check Demo

echo rtrim(str_replace("</a>","</a>,",$output),",");

LF00
  • 27,015
  • 29
  • 156
  • 295
1

I'd argue that the array implode method is probably most common way to concatenate multiple elements like this, which has already been posted in another answer.

Depending on your situation, this might however not always be the case, so for the sake of completion I'd like to add that you can also use the rtrim function to easily remove any trailing commas when concatenating strings:

foreach($links as $link) {
   $output .= '<a>link</a>,';
}
$output = rtrim($output, ',');

Documentation for rtrim can be read here

Daniel Perván
  • 1,685
  • 13
  • 11