php在大写字母前的字符串中放置一个空格(Regex) [英] Php put a space in front of capitals in a string (Regex)
问题描述
我有很多包含单词的字符串,这些单词被捆在一起,我需要将它们分开.
I have a number of strings which contain words which are bunched together and I need to seperate them up.
例如
ThisWasCool-这很酷
MyHomeIsHere-我的家在这里
For example
ThisWasCool - This Was Cool
MyHomeIsHere - My Home Is Here
我正在慢慢了解正则表达式,我相信要做到这一点,我应该使用preg_replace.我的问题是将表达式放在一起以找到匹配项.
Im slowly getting my head around regular expressions and I believe to do this I should use preg_replace. My problem is putting together the expression to find the match.
我只有这么远
preg_replace('~^[A-Z]~', " ", $string)
每个字符串包含很多单词,但是只有第一个单词包含成串的单词,因此在我上面的示例中,字符串将是
"ThisWasCool再次拜访您"-这很酷再次拜访您"
Each string contains a lot of words, but ONLY the first word contains bunched words so using my example above a string would be
"ThisWasCool to visit you again" - "This Was Cool to visit you again"
我已经告诉它要从头开始,并寻找大写字母,但是我不知道该怎么做的是 -仅将其限制为每个字符串的第一个单词 -如何在空格后重复使用替换部分中的大写字母
I have told it to start at the beginning, and look for capitals, but what I dont know how to do is - restrict it only to the first word of each string - how to reuse the capital letter in the replace part after the space
推荐答案
问题
Your regex
'~^[A-Z]~'
will match only the first capital letter. Check out Meta Characters in the Pattern Syntax for more information.
您的替换字符是换行符'\n'
,而不是空格.
Your replacement is a newline character '\n'
and not a space.
解决方案
使用此代码:
Solution
Use this code:
$String = 'ThisWasCool';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
(?<!\ )
是断言确保我们没有在大写字母之前添加空格,而大写字母之前已经有空格.
The (?<!\ )
is an assertion that will make sure we don't add a space before a capital letter that already has a space before it.
这篇关于php在大写字母前的字符串中放置一个空格(Regex)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!