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

I am having trouble finding a function that does exactly what I am looking for. Unfortunately, this feature is not compatible with UTF-8. This function is similar to the basic one ucwords, but it also has an uppercase character followed by one of the given characters (in my case, I need to use an uppercase letter for the character found after -).

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 line, for example:

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

Any idea? I know instead strlenI could use mb_strlen. But what about others?

Edit: Recall that I need not only a simple one ucwordsthat works in UTF-8. I need uppercase to be applied to any character found after -.

.

+3
4

- ucwords. php :

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

, :

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+6

, . -, UTF-8 str_replace ( ). ucwords mb_convert_case strlen mb_strlen...

, :

function my_ucwords($string) {
    $chrs = '"([/-';
    $searchRegex = '/('.preg_quote($chrs, '/').')/u';
    $replaceRegex = '/('.preg_quote($chrs, '/').')\s/u';
    $tmpString = preg_replace($searchRegex, '\1 ', $string);
    $tmpString = mb_convert_case($tmpString, MB_CASE_TITLE);
    return preg_replace($replaceRegex, '\1', $tmpString);
}
0

Source: https://habr.com/ru/post/1769166/


All Articles