Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this string manipulation function UTF-8 Compatible in PHP?

I had trouble finding a function that does exactly what I am looking for. Unfortunatly, this function isn't UTF-8 compatible. This functions is like a basic ucwords but it also does the uppercase on a character followed by one of the given characters found (in my case I need to apply an uppercase on the character found after a -).

Here is the function:

<?php
function my_ucwords($string)
  {
    $noletters='"([/-'; //add more if u need to
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i], $noletters[$i].' ', $string);
    $string=ucwords($string);
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i].' ', $noletters[$i], $string);
    return $string;
  }

$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo my_ucwords(strtolower($title));
?>

As soon as I add accents to my string, e.g.:

echo my_ucwords(strtolower( "saint-étienne" )) //return: Saint- instead of Saint-Étienne

Any idea? I know instead of the strlen I could use mb_strlen. But what about the others?

Edit: Just a reminder that I do not only need a simple ucwords working in UTF-8. I need it to apply the uppercase on any character found after a -.

I'm still trying to figure it out by myself, too.

like image 912
Cybrix Avatar asked Dec 05 '25 07:12

Cybrix


1 Answers

Your problem is ucwords. A quick search on the php page made me discover this:

function mb_ucwords($str) {
    return mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
}

I tested and it works perfectly just remember this line:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
like image 67
0plus1 Avatar answered Dec 07 '25 20:12

0plus1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!