0

我需要对我的字符串应用标题大小写,但有一些例外。

如果子字符串由空格分隔并且仅包含字母,则将第一个字母大写,其余小写。

如果有字母和非字母,则应保持不变:

ucwords(strtolower("NEW APPLE IPHONE X 64GB CVX-Dk46"))

例如:
NEW APPLE IPHONE X 64GB CVX-Dk46

应该变成:
New Apple Iphone X 64GB CVX-Dk46

4

5 回答 5

2

这将遍历每个单词并查看单词中是否有数字,如果没有,则执行 strtolower 和 ucwords。

$str = "NEW APPLE IPHONE X 64GB CVX-Dk46";

$arr = explode(" ", $str); // make it array

foreach($arr as &$word){ // loop array
    if(!preg_match("/\d/", $word)){ // is there not a digit in the word
        $word = ucwords(strtolower($word));
    }
}

echo implode(" ", $arr); // implode array to string
//New Apple Iphone X 64GB CVX-Dk46

https://3v4l.org/qccG9

于 2019-01-31T07:47:32.277 回答
1

这是另一种方法。唯一的区别是在 Andreas 的回答中使用了array_walk()函数而不是循环。foreach()(这也是一个很好的答案。)

$str = 'NEW APPLE IPHONE X 64GB CVX-Dk46';

$data = explode(' ', $str); //This will take the sting and break the string up
//into an array using the space bewtween the words to break apart the string.

array_walk($data, function(&$item){  //Walk each item in the array through a function to decide what gets UC letter.

  if(!preg_match('/\d/', $item)){ //Test for any numbers in a word.

    //If there are no numbers convert each character to lower case then upper case the first letter.
    $item = ucwords(strtolower($item));

  }

});

$newString = implode(' ', $data);  //Take the new array and convert it back to a string.

echo $newString; //This will output:  "New Apple Iphone X 64GB CVX-Dk46"
于 2019-01-31T07:56:34.283 回答
0

你不能用一行来实现这一点。如果它对你有帮助,请参阅下面的代码。

$val = "NEW APPLE IPHONE X 64GB CVX-Dk46";
$val = explode(" ", $val);
$finalString = '';
foreach ($val as $value) {
 if(preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $value)) { 
   $finalString = $finalString . " " . ucwords(strtolower($value));
 } else {
 $finalString = $finalString . " " . $value;
 }
}
echo $finalString;  

输出将如下: -

New Apple Iphone X 64GB CVX-Dk46
于 2019-01-31T07:57:03.200 回答
0

首先你需要在你的字符串中找到数字 - 如果有你需要将你的字符串分隔为数组的数字第一个数组只包含字符串,第二个数组包含数字(或数字和字符串) - 如果没有您需要使用 php 函数 strtolower 来降低字符串并使用 php 函数 ucwords 将字符串的第一个字符转换为大写您可以尝试以下代码:链接:https ://3v4l.org/jW6Wf

function upperCaseString($string)
{
$pattern = '/(?=\d)/';
$array = preg_split($pattern, $string, 2);
$text='';
	if(count($array)>1)
	{
		
		$text=ucwords(strtolower($array[0])).' '.strtoupper($array[1]);
	}
	else
	{
		$text=ucwords(strtolower($array[0]));
	}
	return $text;
}
$str = "NEW APPLE IPHONE X 64GB CVX-Dk46";
echo upperCaseString($str);

于 2019-01-31T10:24:06.480 回答
0

对于您的示例字符串,这可以通过调用中的单个匹配子字符串preg_replace_callback()来实现!

代码:(演示)(正则表达式演示

echo preg_replace_callback(
         '~(?:\G ?)\p{Lu}+(?= |$)~u',
         function($m) {
             return mb_convert_case($m[0], MB_CASE_TITLE);
         },
         'NEW APPLE IPHONE X 64GB CVX-Dk46'
     );
// New Apple Iphone X 64GB CVX-Dk46

\G继续元字符)从字符串的开头开始匹配,或者从模式先前停止匹配的位置开始匹配。我正在使用空格和锚来满足匹配整个 ALL-CAPS 单词的要求。

这比嵌套的环视表现更好。例如(?:(?:^| )\p{Lu}+(?= |$))+

于 2021-08-13T11:48:15.327 回答