根据条件向字符串添加空格


Adding space to string based on condition

我有很多标签,它们都是驼色大小写的。就是一些例子

whatData
whoData
deliveryDate
importantQuestions  

我想做的就是这个。任何带有"数据"一词的标签都需要删除该词。就大写字母而言,我需要提供一个空格。最后,所有内容都应该是大写的。我已经通过这样做删除了数据和大写字母($Data->key是标签)

strtoupper(str_replace('Data', '', $data->key))

我正在努力增加单词之间的空格。所以基本上,上面的单词应该像这个一样结束

WHAT
WHO
DELIVERY DATE
IMPORTANT QUESTIONS

我该如何考虑这最后一部分?

感谢

它会在每个大写字母之前添加空格。试试这个:

$String = 'whatData';
$Words = preg_replace('/(?<!' )[A-Z]/', ' $0', $String);

问题

  • 正则表达式'~^[A-Z]~'将只匹配第一个大写字母。有关详细信息,请查看模式语法中的元字符
  • 替换项是换行符''n',而不是空格

解决方案

使用preg_replace()。请尝试以下代码。

$string = "whatData";   
echo preg_replace('/(?<!' )[A-Z]/', ' $0', $string);

输出

what Data

尝试以下操作:

$string = 'importantQuestions';
$string = strtoupper(ltrim(preg_replace('/[A-Z]/', ' $0', $string)));
echo $string;    

这将为您提供以下输出:

重要问题

试试这个:

preg_split:  split on camel case
array_map:   UPPER case all the element
implode:     Implode the array
str_replace: Replace the `DATE` with empty
trim:        trim the white spaces.

做这些简单的事情:

echo trim(str_replace("DATE", "", implode(" ", array_map("strtoupper", preg_split('/(?=[A-Z])/', 'deliveryDate', -1, PREG_SPLIT_NO_EMPTY))))); // DELIVERY

这正是你们想要的结果。