在每个大写字母之前拆分 PascalCase 单词字符串

问题描述 投票:0回答:2

我有这样的字符串:

SadnessSorrowSadnessSorrow

单词连接在一起,没有任何空格。每个单词都以大写字母开头。我想分隔这些单词并选择前 2 个单词放入新字符串中。

我需要在 php 应用程序中使用

preg_match
函数来执行此操作。

我该怎么办?

我尝试使用

[A-Z]
,但不知何故我没有得到正确的结果。

php cpu-word uppercase preg-split pascalcasing
2个回答
3
投票

这里,我们还可以用大写字母分割字符串,可能类似于:

$str = "SadnessSorrowSadnessSorrow";

$str_array = preg_split('/\B(?=[A-Z])/s', $str);

foreach ($str_array as $value) {
    echo $value . "\n";
}

根据bobble bubble的建议,最好使用

\B(?=[A-Z])
而不是
(?=[A-Z])
,或者我们可以使用
PREG_SPLIT_NO_EMPTY

输出

Sadness
Sorrow
Sadness
Sorrow

1
投票

问题一出,答案就闪现:

preg_match_all('([A-Z][a-z]+)', 'SadnessSorrowSadnessSorrow', $matches);

它给出:

(
[0] => Sadness
[1] => Sorrow
[2] => Sadness
[3] => Sorrow
)
© www.soinside.com 2019 - 2024. All rights reserved.