phpprefixdelimited

Prepend character to each value in a delimited string


I am trying to take a string like php,mysql,css
and turn it into #php #mysql #css

What I have so far:

$hashTagStr  = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);

foreach($hashTags as $k => $v){
    $hashTagsStr = '';
    $hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;

Problem is it only prints #css


Solution

  • How about this:

    $hashTagStr  = "php,mysql,css";
    $hashTags = explode(",", $hashTagStr);
    $hashTagStr = '#' . implode( ' #', $hashTags );
    

    ...or:

    $hashTagStr  = "php,mysql,css";
    $hashTagStr = '#' . str_replace( ',', ' #', $hashTagStr );