Skip to content
Advertisement

Combine ucwords and strtoupper in a string with symbol as separator

I have some of string which look like this :

“MOULDED WIRE BRA #viag19203”

“moulded non wire bra #viag19202”

how to make all the string to become like :

“Moulded Wire Bra #VIAG19203”

“Moulded non-Wire Bra #VIAG19203”

so every word before # is using ucwords, and everything after ‘#’ is strtotupper

the closest solution i can find for now is

<?php
$txt = "moulded non wire bra #viag19202";

echo implode('#', array_map('ucwords', explode('#', $txt)));

?>

the result is :

Moulded Non Wire Bra #Viag19202

how to make all the letter after # uppercase?

Advertisement

Answer

You can use strpos to find first position of #: Then you can slice your string with substr and use ucwords on first and the strtoupper on second:

$txt = "moulded non wire bra #viag19202";
$position = strpos($txt, '#'); 
$first = ucwords(substr($txt, 0, $pos));
$second = strtoupper(substr($txt, $pos));
$label = $first.$second;

echo $label;

Or using implode and explode. You had an error, because you was using ucwords on each element of array:

$txt = "moulded non wire bra #viag19202";
$chunks = explode('#', $txt);
$chunks[0] = ucwords($chunks[0]);
$chunks[1] = strtoupper($chunks[1]); //#viag19202" -->> #VIAG19203

echo implode('#', $chunks);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement