对于带有数字的子字符串,以不同的方式更改字符串的大小写

时间:2019-01-31 07:31:43

标签: php string case

我需要以子字符串的不同方式更改字符串的PHP大小写。

如果子字符串由空格和仅字母分隔,则首字母大写,其余字母小写。
如果有字母和数字,它们仍应以大写形式邮寄:

此PHP 5。

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

例如:

  

新苹果IPHONE X 64GB CVX-Dk46

应成为:

  

新的Apple Iphone X 64GB CVXDk46

4 个答案:

答案 0 :(得分:2)

这将循环遍历每个单词,查看单词中是否有数字,如果没有,则使用strtolower和ucword。

$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

答案 1 :(得分: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"

答案 2 :(得分: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

答案 3 :(得分: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);