- Explode your string.
- Trim outer spaces from each element.
- Replace inner spaces with hyphen in each element.
- Only keep non-empty elements.
- Only keep unique elements (using double array_flip).
- Display results.
Code: (Demo)
while($rez=$result->fetch_assoc()) {
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){$clean[]=$v;} // retain non-empty values
}
$clean=array_flip(array_flip($clean)); // double flip is faster than array_unique
foreach($clean as $v){
echo "<a href=\"http://example.com/$v\">$v</a><br>";
}
}
Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch. This will remove the potentially unnecessary trailing
from final element:
Code:
$rez['tags']=' , word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){
$clean[]="<a href=\"http://example.com/$v\">$v</a>"; // prep non-empty values for display
}
}
echo implode("<br>",array_unique($clean));
Output:
<a href="http://example.com/word">word</a><br>
<a href="http://example.com/word-word">word-word</a><br>
<a href="http://example.com/word2">word2</a><br>
<a href="http://example.com/word3">word3</a>