从字符串开头删除数字,然后删除空格
我将如何从字符串开头删除数字和空格?
例如,从“13 Adam Court, Cannock”中删除“13”
How would I go about removing numbers and a space from the start of a string?
For example, from '13 Adam Court, Cannock' remove '13 '
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为其他人都走 \d+\s 路线,我会给你一个脑死亡的答案,
明智的人,不要使用 / 作为正则表达式中的分隔符,你会经历可怕的倾斜-尝试执行文件路径或类似 http://
:)时的牙签问题
Because everyone else is going the \d+\s route I'll give you the brain-dead answer
Word to the wise, don't use / as your delimiter in regex, you will experience the dreaded leaning-toothpick-problem when trying to do file paths or something like http://
:)
使用我在 中给出的相同正则表达式JavaScript 答案,但使用
preg_replace()
应用它:Use the same regex I gave in my JavaScript answer, but apply it using
preg_replace()
:我会使用
/^\d+\s+/
它在字符串开头查找任意大小的数字
^ \d+
然后查找后面的空格
\s+
当您在某些字母之前使用反斜杠时,它代表某些内容。 ..
\d
代表数字0,1,2,3,4,5,6,7,8,9
。\s
代表空格。
在末尾添加一个加号 (
+
),您可以得到...\d+
一系列数字(数字)\s+
多个空格(拼写错误等)I'd use
/^\d+\s+/
It looks for a number of any size in the beginning of a string
^\d+
Then looks for a patch of whitespace after it
\s+
When you use a backslash before certain letters it represents something...
\d
represents a digit0,1,2,3,4,5,6,7,8,9
.\s
represents a space.
Add a plus sign (
+
) to the end and you can have...\d+
a series of digits (number)\s+
multiple spaces (typos etc.)试试这个:
像这样:
资源:
同一主题:
Try this one :
Like this :
Resources :
On the same topic :
我给你的相同正则表达式其他问题仍然适用。您只需使用
preg_replace()
即可。搜索
/^[\s\d]+/
并替换为空字符串。例如:这将从字符串开头以任意顺序删除数字和空格。对于仅删除数字后跟空格的内容,请参阅 BoltClock 的答案。
The same regex I gave you on your other question still applies. You just have to use
preg_replace()
instead.Search for
/^[\s\d]+/
and replace with the empty string. Eg:This will remove digits and spaces in any order from the beginning of the string. For something that removes only a number followed by spaces, see BoltClock's answer.
如果输入字符串都具有相同的预期格式,并且您将通过左修剪所有数字和空格收到相同的结果(无论它们在字符串前面出现的顺序),那么您实际上不需要启动正则表达式引擎。
我喜欢正则表达式,但知道不要使用它,除非它比非正则表达式技术提供了有价值的优势。正则表达式通常比非正则表达式技术慢。
将
ltrim()
与包含空格和数字的字符掩码结合使用。代码:(Demo)
输出:
字符串是否以空格开头也没关系。
ltrim()
会贪婪地删除字符串开头的所有空格或数字实例,直到无法再删除为止。If the input strings all have the same ecpected format and you will receive the same result from left trimming all numbers and spaces (no matter the order of their occurrence at the front of the string), then you don't actually need to fire up the regex engine.
I love regex, but know not to use it unless it provides a valuable advantage over a non-regex technique. Regex is often slower than non-regex techniques.
Use
ltrim()
with a character mask that includes spaces and digits.Code: (Demo)
Output:
It wouldn't matter if the string started with a space either.
ltrim()
will greedily remove all instances of spaces or numbers from the start of the string intil it can't anymore.