2

I know how to use str_replace(' ', '<span></span>', $text);

But is there any way I can get a result like

cat, dog, elephant, pig 

to be converted like

<span class="tagstyle">cat</span><span class="tagstyle">dog</span><span class="tagstyle">elephant</span><span class="tagstyle">pig</span>

Either in PHP, jQuery is it possible to replace comma separated value like a span method?

1
  • 1
    in php echo '<span class="tagstyle">' . implode('</span><span class="tagstyle">', explode(',','cat, dog, elephant, pig ')) . '</span>'; Commented Jul 3, 2014 at 12:08

4 Answers 4

4

In PHP it could be:

<?php

$string = 'cat, dog, elephant, pig';
$animals = explode(',', $string);
$output = '';

foreach ($animals as $animal) {
    $output .= '<span class="tagstyle">' . trim($animal) . '</span>';
}

echo $output;

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

Comments

2

you can do like this:

var animals = "cat, dog, elephant, pig";
var temp = animals.split(',');
var html = '';
$.each(temp, function (index, item) {
    console.log(item);
    html += '<span class="tagstyle">' + item + '</span>';

})

$("#contain").html(html);

FIDDLE EXAMPLE

Comments

2

Try to use $.map() to translate the array to our required format, then join that array with empty string,

var str = "cat,dog,elephant,pig";
var htmlString = $.map(str.split(','),
    function(val,i){ 
     return '<span class="tagstyle">'+ val + '</span>'; 
}).join('');  //<span class="tagstyle">cat</span> .......

DEMO

Comments

0

If it's just simple like that, you can try:

'<span class="tagstyle">'.str_replace(', ','</span><span class="tagstyle">',$text).'</span>';

or

$array = explode(', ',$text);
$newText = '<span class="tagstyle">'.implode('</span><span class="tagstyle">',$array).'</span>';

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.