ucwords는 기본적으로 공간별로 분리 된 단어의 첫 번째 문자 만 대문자를 대용하지만 하이픈 (-), 밑줄 (_) 등과 같은 문자열에 다른 분리기가있는 경우 ucwords는 그것을 인식하지 못합니다.
<?php
$title = "my-php_script example";
$formatted = ucwords($title);
echo $formatted; // 산출:My-php_script Example
?>
현재 "php_script"는 여전히 소문자이며 올바르게 형식화되지 않습니다.
방법 방지 방법 : 분리기를 사용자 정의하거나 다른 분리기를 먼저 공백으로 교체 한 다음 처리 후 복원 할 수 있습니다.
<?php
function ucwords_custom($string, $delimiters = ['-', '_']) {
foreach ($delimiters as $delimiter) {
$string = str_replace($delimiter, ' ', $string);
}
$string = ucwords($string);
foreach ($delimiters as $delimiter) {
$string = str_replace(' ', $delimiter, $string);
}
return $string;
}
echo ucwords_custom("my-php_script example"); // 산출:My-PHP_Script Example
?>
입력 문자열이 이미 부분적으로 또는 완전히 자본화 된 경우 ucwords를 직접 사용하면 결과에 혼동이 발생할 수 있습니다.
<?php
$title = "tHe quick bROWN foX";
$formatted = ucwords($title);
echo $formatted; // 산출:THe Quick BROWN FoX
?>
현재 일부 단어는 여전히 상류 및 소문자와 혼합되어 있으며 제목 형식은 달성되지 않습니다.
피하십시오 : 먼저 문자열을 모든 소문자로 통합 한 다음 ucwords를 사용하십시오.
<?php
$title = "tHe quick bROWN foX";
$formatted = ucwords(strtolower($title));
echo $formatted; // 산출:The Quick Brown Fox
?>
ucwords는 일반 텍스트와 잘 어울리지 만 문자열에 HTML 태그 또는 URL이 포함되어 있으면 전화를 직접 태그와 링크를 파괴합니다.
<?php
$title = 'visit <a href="https://gitbox.net/path">our site</a>';
echo ucwords($title);
// 결과는 오류 처리 된 레이블입니다,~이 되다 Visit <A Href="Https://Gitbox.Net/Path">Our Site</A>
?>
피하십시오 : 먼저 태그를 추출하거나 텍스트 부품을 처리 한 다음 다시 연결하거나 URL을 보호 할 수 있습니다. 쉬운 방법은 HTML 태그를 건너 뛰는 것입니다.
<?php
function ucwords_without_tags($text) {
return preg_replace_callback('/([^<>]+)(?=<|$)/', function($matches) {
return ucwords(strtolower($matches[1]));
}, $text);
}
echo ucwords_without_tags('visit <a href="https://gitbox.net/path">our site</a>');
// 산출:Visit <a href="https://gitbox.net/path">Our Site</a>
?>