使用php preg_match将驼峰大小写单词拆分为单词(正则表达式)

2022-08-30 08:33:54

我该如何拆分这个词:

oneTwoThreeFour

放入数组中,以便我可以得到:

one Two Three Four

跟?preg_match

我厌倦了这个,但它只是给出了整个词

$words = preg_match("/[a-zA-Z]*(?:[a-z][a-zA-Z]*[A-Z]|[A-Z][a-zA-Z]*[a-z])[a-zA-Z]*\b/", $string, $matches)`;

答案 1

您可以使用:preg_split

$arr = preg_split('/(?=[A-Z])/',$str);

看到它

我基本上是在大写字母之前拆分输入字符串。使用的正则表达式与大写字母前面的点匹配。(?=[A-Z])


答案 2

您还可以用作:preg_match_all

preg_match_all('/((?:^|[A-Z])[a-z]+)/',$str,$matches);

解释:

(        - Start of capturing parenthesis.
 (?:     - Start of non-capturing parenthesis.
  ^      - Start anchor.
  |      - Alternation.
  [A-Z]  - Any one capital letter.
 )       - End of non-capturing parenthesis.
 [a-z]+  - one ore more lowercase letter.
)        - End of capturing parenthesis.

推荐