split a string into links using the comma
<p>this is a common function for some field data, lets say you have a string like this.</p>
<p>category one, category two, another category in one field or string</p>
<p>but i want it to display like this</p>
<p><a href="#link1">category one</a>, <a href="#link2">category two</a>, <a href="#link3">another category</a></p>
<p><strong>How can i do this consistantly based on the comma?</strong></p>
<p>I think the best way (or at least one easy way) to do this would be to use the explode function in php. As the explode function takes one (or more) character in the string and then splits the string into an array.</p>
<h4>PHP - Explode Function</h4>
<pre><code class="php hljs"><span class="methodparam"><code class="parameter">explode(string $separator, string $string, int $limit = PHPINTMAX): array</code></span></code></pre>
<p>then once its an array we can loop through each element and add this to the format that we require.</p>
<p>also you can remove the trailing comma from the last item with</p>
<h4>PHP</h4>
<pre><code class="php hljs">$catslinkshtml = rtrim($catslinkshtml,", ");</code></pre>
PHP
// this splits the string into an array and then loops through the array
$cats = "category one, category two, another category";
$cats_array = explode(",",$cats);
$cats_html = "";
foreach ($cats_array as $cat_key => $cat_value) {
$cats_html .= "\$cat_key: $cat_key = \$cat_value: $cat_value <br>";
}
echo $cats_html;
// now we can add the links
// also added a trim and urlencode and htmlentities there to make sure we dont have any excess spaces or html breaking / urlbreaking characters in there
$cats_links_html = "";
foreach ($cats_array as $cat_key => $cat_value) {
$cat_value_urlenc = urlencode(trim($cat_value));
$cat_value_html_safe = htmlentities($cat_value);
$cats_links_html .= "<a href='#$cat_value_urlenc'>$cat_value_html_safe</a>, ";
}
echo $cats_links_html;
$cat_key: 0 = $cat_value: category one $cat_key: 1 = $cat_value: category two
$cat_key: 2 = $cat_value: another category
category one, category two, another category