0

I have a variable $var and it contain comma separated value.

$var = 'the_ring,hangover,wonder_woman';

I want to make it like below.

$var = 'The Ring,Hangover,Wonder Woman';

I tried $parts = explode(',', $var); also I tried strpos() and stripos() but not able to figure it out.

What can I do to achieve this?

8
  • Is there a reason you're using a string rather than an array? Commented Jun 4, 2017 at 17:41
  • data is coming from database actually. Commented Jun 4, 2017 at 17:42
  • why is the 2nd $var in Camel Case? Commented Jun 4, 2017 at 17:42
  • @Fred-ii- These are movie titles, which would be Camel Case :) Commented Jun 4, 2017 at 17:44
  • @Fred-ii- do i need to implode the array data. So, i can get the single variable. Commented Jun 4, 2017 at 17:53

6 Answers 6

4
$var = 'the_ring,hangover,wonder_woman';

$list = explode(',', $var);

$list = array_map( function($name){
    return ucwords(str_replace('_',' ', $name));
}, $list);

Returns:

Array
(
    [0] => The Ring
    [1] => Hangover
    [2] => Wonder Woman
)

Imploding:

$imploded = implode(',', $list);

Returns:

'The Ring,Hangover,Wonder Woman'
Sign up to request clarification or add additional context in comments.

2 Comments

i need to implode the array then because they need data in single variable.
Man, Why do you have to write too many lines of code to achieve something, which can be done with few lines of code?
2

You can use array_walk to do your replace and uppercase:

$var = 'the_ring,hangover,wonder_woman';

$parts = explode(',', $var);

array_walk($parts, function(&$item){
    $item = str_replace('_', ' ', $item);
    $item = ucwords($item);
});

$var = implode(',', $parts);

1 Comment

This only makes the first word upper case - FYI
1

Using str_replace() function click here to explain

like this code

$str= 'the_ring,hangover,wonder_woman';

echo str_replace("_"," ","$str");

Comments

1

This is how you replace _ with white spaces using str_replace() function

$var = 'the_ring,hangover,wonder_woman';
echo str_replace("_"," ",$var);

Comments

1
$var = 'the_ring,hangover,wonder_woman';
$var1 = explode(',' $var);

foreach ($var1 as $key => $value) {
   $var1[$key]=str_replace("_"," ",$value);
   $var1[$key]=ucwords($var1[$key]);
}

$var = implode(',', $var1);

Comments

-1

1.use str_replace to replace something in the string. In your case _ is replaced with space 2.use ucFirst method to capitalize every first character in the strings

$replaced = str_replace('_', ' ', $var);
$changed = ucfirst($replaced);

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.