Сравнивая с 3 альтернативами, я считаю, что ваш метод самый быстрый. Вот результаты 100 000 итераций:
array(4) {
["Test1"]=>
float(0.23144102096558)
["Test2"]=>
float(0.41140103340149)
["Test3"]=>
float(0.31215810775757)
["Test4"]=>
float(0.98423790931702)
}
Где Test1
— ваше, Test2
и Test3
— мое, а Test4
— из ответа @RizwanMTuman (с исправлением).
Я подумал, что использование preg_split
может дать вам возможность оптимизировать. В этой функции используется только одно регулярное выражение, которое возвращает массив только альфа-элементов, к которым вы затем применяете ucfirst
:
function FoxJourneyLikeACamelsHump_2(string $string): string {
return implode('', array_map(function($word) {
return ucfirst($word);
}, preg_split("/[^[:alpha:]]/", $string, null, PREG_SPLIT_NO_EMPTY)));
}
Это можно дополнительно оптимизировать, используя foreach
вместо array_map
(см. with-static-function">здесь):
function FoxJourneyLikeACamelsHump_3(string $string): string {
$validItems = preg_split("/[^[:alpha:]]/u", $string, null, PREG_SPLIT_NO_EMPTY);
$result = '';
foreach($validItems as $item) {
$result .= ucfirst($item);
}
return $result;
}
Это заставляет меня предположить, что 2 регулярных выражения и 1 ucwords
быстрее, чем 1 регулярное выражение и несколько ucfirst
.
Полный тестовый скрипт:
<?php
// yours
function FoxJourneyLikeACamelsHump_1(string $string): string {
$string = preg_replace("/[^[:alpha:][:space:]]/u", ' ', $string);
$string = ucwords($string);
$camelCase = preg_replace('/\s+/', '', $string);
return $camelCase;
}
// mine v1
function FoxJourneyLikeACamelsHump_2(string $string): string {
return implode('', array_map(function($word) {
return ucfirst($word);
}, preg_split("/[^[:alpha:]]/", $string, null, PREG_SPLIT_NO_EMPTY)));
}
// mine v2
function FoxJourneyLikeACamelsHump_3(string $string): string {
$validItems = preg_split("/[^[:alpha:]]/u", $string, null, PREG_SPLIT_NO_EMPTY);
$result = '';
foreach($validItems as $item) {
$result .= ucfirst($item);
}
return $result;
}
// Rizwan with a fix
function FoxJourneyLikeACamelsHump_4(string $string): string {
$re = '/(?:\b|\d+)([a-z])|[\d+ +!.@]/';
$result = preg_replace_callback($re,function ($matches) {
return (isset($matches[1]) ? strtoupper($matches[1]) : '');
},$string);
return $result;
}
// $expected = "ThQuCkBrWnFXJumpsVRThLZyDG";
$test1 = 0;
$test2 = 0;
$test3 = 0;
$test4 = 0;
$loops = 100000;
$time_start = microtime(true);
for($i=0; $i<$loops; $i++) {
$string = " Th3 qu!ck br0wn f0x jumps 0v3r th3 l@zy d0g. ";
$is = FoxJourneyLikeACamelsHump_1($string);
if($loops==1) echo $is."\n";
}
$time_end = microtime(true);
$test1 = $time_end - $time_start;
$time_start = microtime(true);
for($i=0; $i<$loops; $i++) {
$string = " Th3 qu!ck br0wn f0x jumps 0v3r th3 l@zy d0g. ";
$is = FoxJourneyLikeACamelsHump_2($string);
if($loops==1) echo $is."\n";
}
$time_end = microtime(true);
$test2 = $time_end - $time_start;
$time_start = microtime(true);
for($i=0; $i<$loops; $i++) {
$string = " Th3 qu!ck br0wn f0x jumps 0v3r th3 l@zy d0g. ";
$is = FoxJourneyLikeACamelsHump_3($string);
if($loops==1) echo $is."\n";
}
$time_end = microtime(true);
$test3 = $time_end - $time_start;
$time_start = microtime(true);
for($i=0; $i<$loops; $i++) {
$string = " Th3 qu!ck br0wn f0x jumps 0v3r th3 l@zy d0g. ";
$is = FoxJourneyLikeACamelsHump_4($string);
if($loops==1) echo $is."\n";
}
$time_end = microtime(true);
$test4 = $time_end - $time_start;
var_dump(array('Test1'=>$test1, 'Test2'=>$test2, 'Test3'=>$test3, 'Test4'=>$test4));
person
Robin Mackenzie
schedule
08.04.2017
ucwords
илиucfirst
, которые не поддерживают юникод. - person Casimir et Hippolyte   schedule 08.04.2017