How to convert a string to a camel case with non-alphanumeric characters?

I need to convert a string to a camel case, easily using:

mb_convert_case($str, MB_CASE_TITLE, "UTF-8")

But what if the string contains non-alphanumeric characters:

$str = 'he said "hello world"';
echo mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

Result:

He Said "hello World"

But I need:

He Said "hello World"

How can we handle this?

thank

+3
source share
5 answers

With regex.

If you intend to work with Latin letters without an accent, it can be as simple as

$str = 'he said "hello WORLD"';
echo preg_replace('/\b([a-z])/e', 'strtoupper(\'$1\')', strtolower($str));

This matches any lowercase Latin letter that is preceded by a word boundary . The letter is replaced with its upper case.

If you want this to work with other languages ​​and scripts, you will need to pretend:

$str = 'he said "καλημέρα ΚΌΣΜΕ"'; // this has to be in UTF-8
echo preg_replace('/(?<!\p{L})(\p{Ll})/eu',
                  'mb_convert_case(\'$1\', MB_CASE_UPPER, \'UTF-8\')',
                  mb_convert_case($str, MB_CASE_LOWER, 'UTF-8'));

, Unicode PCRE , u preg_replace. , ( \p{Ll}), , - (negative lookbehind \p{L}). .

.

: , .

(?<=\s|^)([a-z])
(?<=\s|^)(\p{Ll})
+2

- ( PHP.net)

$str = 'he said "hello world"';
echo preg_replace('/([^a-z\']|^)([a-z])/ie', '"$1".strtoupper("$2")', strtolower($str));
0

!: D php.net

<?php

function ucwordsEx($str, $separator){

      $str = str_replace($separator, " ", $str);
      $str = ucwords(strtolower($str));
      $str = str_replace(" ", $separator, $str);
      return $str;

}
/*
Example:
*/
echo ucwordsEx("HELLO-my-NAME-iS-maNolO", "-");
/*
Prints: "Hello My Name Is Manolo"
*/

?>
0

, , , :

preg_replace('/\b([a-z])/e', 'strtoupper("$1")', strtolower($str));
0

echo  ucwords('he said '.ucwords('"hello world"')) ;

output He said Hello World

0
source

All Articles