我有这样的字符串:
SadnessSorrowSadnessSorrow
单词连接在一起,没有任何空格。每个单词都以大写字母开头。我想分隔这些单词并选择前 2 个单词放入新字符串中。
我需要在 php 应用程序中使用
preg_match
函数来执行此操作。
我该怎么办?
我尝试使用
[A-Z]
,但不知何故我没有得到正确的结果。
这里,我们还可以用大写字母分割字符串,可能类似于:
$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
问题一出,答案就闪现:
preg_match_all('([A-Z][a-z]+)', 'SadnessSorrowSadnessSorrow', $matches);
它给出:
(
[0] => Sadness
[1] => Sorrow
[2] => Sadness
[3] => Sorrow
)