根据最后出现的下划线分割字符串
我有由标签、下划线和 ID 组成的字符串:
- "category_4"
- "office_362"
- "core_market_56"
我想要的是两个不同的块:
- array("category", 4)
- array("office ", 362)
- array("core_market", 56)
我知道我可以隔离数值,然后转身并从原始字符串中减去该数值,但我不确定是否可以有一种更简洁的方法可以一步完成此操作。 Explode 的 limit
参数看起来很接近,我有一种感觉,有一个正则表达式模式只能被最后一个下划线分割。
I've got strings which consist of a label, underscores, and an ID:
- "category_4"
- "office_362"
- "core_market_56"
What I'd like to have are two distinct chunks:
- array("category", 4)
- array("office", 362)
- array("core_market", 56)
I know that I can isolate the numeric value, then turn around and subtract that from the original string, but I'm not sure if there's a cleaner way to do this in one step. Explode's limit
argument seems close, and I have a feeling there's a regex pattern that could split by only the last underscore.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是您想要的正则表达式
第一个匹配组是您的单词,第二个匹配组是数字。当然,这是基于这样的假设:数字始终位于末尾,并且通过下划线与单词分隔。
This is the regex you want
First matched group is your word, second - number. This is based, of course, on the assumption that number is always in the end and is separated from the word by underscore.
上面会返回
The above will return
我认为用于解析目的的最有效方法是在末尾有一个固定长度数字字段,以便您始终可以计算从末尾开始的准确字符数字符串并知道其余部分(减去分隔符)将是文本部分。
I figure the most efficient way for parsing purposes is to have a fixed length numeric field at the end so that you can always count an exact number of characters from the end of the string and know that the rest (minus the separator) will be the text portition.
要仅根据最后出现的下划线进行分割,请使用对字符串开头的“任何”字符进行贪婪匹配的模式,然后在遇到最后出现的下划线之前重置全字符串匹配。这将有效地仅消耗最后一个下划线,并将字符串最多分成两部分。您得到的正是您想要使用的二元素数组。
preg_match()
将返回三元素数组,其中第一个元素对您没有用处。代码:(演示)
输出:
To split only on the last occurring underscore, use a pattern with a greedy match on "any" characters from the start of the string, then reset the fullstring match just before encountering the last occurring underscore. This will effectively consume the last underscore only and split the string into two parts at most. You get exactly what you intend to use, two-element arrays.
preg_match()
will return three-element arrays, of which the first element is of no use to you.Code: (Demo)
Output: