0

Quick question,

I have the following string which is a coma separated list of tags:

$tagcap = "tag1, tag2, tag3";

How do I go about obtaining a single string that looks like this:

$string = "#tag1, #tag2, #tag3;

In other words, simply adding # in front of each word?

Thanks!

Edit:

Thanks a lot, that seems perfect except it also adds a # infront of words with hyphens, for example: self-shot becomes #self-#shot, how can I fix this?

Edit 2: Thanks for fast help guys, issue fixed!

1
  • if that was really your string, str_replace(), but i bet its not. and you want help? Commented Jun 7, 2012 at 7:24

5 Answers 5

3

Use regular expression:

$str = preg_replace('/(\w+)/', '#$1', $str);

Update:

To include - char, use

$str = preg_replace('/([a-z0-9-]+)/i', '#$1', $str);

Where ([a-z0-9]+) will match with any letter, number, and - chars. The i flag will make it case-insensitive.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot, that seems perfect except it also adds a # infront of words with hyphens, for example: self-shot becomes #self-#shot, how can I fix this?
@Sherif Please update your question to list the various types of formats you'll be accomodating.
that's what happens when you use an "example" use the real values or don't bother asking
I used an example because the string is made of variables, I was lucky to find this issue with the one I tested. No need to be rude @dagon
@Sherif sorry for the typho. See JonathanSampon's answer instead. I wanted to type the regex like his answer but I missed some chars :)
1
$tagcap = "tag1, tag2, self-shot";
echo preg_replace( "/([a-z0-9-_]+)/i", "#$1", $tagcap );

Which outputs:

#tag1, #tag2, #self-shot

This prefixes any series of letters, numbers, dashes (-), or underscores with a hash (#).

Demo: http://codepad.org/0WgaZg2L

1 Comment

I kept this tab open to accept it today, it hadn't been long enough last night and I had to head to bed ;) Thanks again for your help!
0

Try this one:

$tagcap = "tag1, tag2, tag3";

$tagcap = str_replace("t","#t",$tagcap );
echo $tagcap;

Comments

0

You could also use this, but this is other alternate using php functions.

<?php
$tagcap = "tag1, tag2, tag3";
$res = explode(',',$tagcap);
$values = array();
foreach($res as $key=>$value){
  if(isset($value)){
  $values[] = '#'.$value;
}

$finalResult = implode('',$values);
echo $finalResult;
}
?>

Comments

0

Here's another solution without Regex:

$string = "tag1,tag2,tag3";
function addPrefix(&$item,$key,$prefix)
{
   $item = $prefix.$item;
}

$arr = explode(",",$string);
array_walk($arr,"addPrefix","#");
echo implode($arr,","); //output "#tag1,#tag2,#tag3"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.