How does one break a string down by capital letters with PHP?

自闭症网瘾萝莉.ら 提交于 2019-12-06 05:11:05

问题


I have a string: CamelCaseString

I want to explode(), split(), or some better method on capital letters to break this string down into the individual words.

What's the simplest way to do this?

--- SOLUTION UPDATE ---

This link is to a slightly different question, but I think the answer will generally be more useful than the answers to the current question on this page: How can I add a space in string at capital letters, but keep continuous capitals together using PHP and a Regex?


回答1:


You should use regular expressions. Try this: preg_match_all('/[A-Z][^A-Z]*/', "CamelCaseString", $results);

The array containing all the words will be saved in $results[0].




回答2:


This seems to work too

$split = preg_split("/(?<=[a-z])(?![a-z])/", "CamelCaseString", -1, PREG_SPLIT_NO_EMPTY);

And it won't break up longer runs of uppercase letters. I.e. "MySQL", will become "My" and "SQL"




回答3:


The split() function has been deprecated so I would look for a solution that uses some other function.



来源:https://stackoverflow.com/questions/6920155/how-does-one-break-a-string-down-by-capital-letters-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!