删除字符串中从第二个出现的连字符开始的所有字符
如何在字符 -
第二次出现后删除字符串中的所有内容?
例如:今天是 - 星期五,明天是 - 星期六
我希望将 星期六
连同最后一个连字符一起删除:- 星期六
我只能似乎在第一个 -
之后删除所有内容。
预期结果是:今天是 - 星期五,明天是
How can I strip everything in a string after the character -
has occurred for the second time?
For example: Today is - Friday and tomorrow is - Saturday
I want Saturday
to be removed along with the last hyphen: - Saturday
I can only seem to get everything to be removed after the first -
.
The expected result is: Today is - Friday and tomorrow is
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
编辑:请注意,正如下面@mickmackusa 所指出的,如果连字符少于两个,这将返回一个空字符串。结束编辑。
使用 strpos 查找第一个出现的位置,然后再次使用它来查找指向的点结束使用带有先前值的偏移选项。然后使用 substr。
Edit: Please note as noted by @mickmackusa below, this will return an empty string if there are less than two hyphens. End Edit.
Use strpos to find the first occurrence and use it again to find the point to end using the offset option with the value from previous. Then use substr.
一些爆炸怎么样:
How about some explosions:
另一种使用
strtok
的方法:演示
Another way with
strtok
:DEMO
对于其他有同样问题的人;我使用了这种易于调整的紧凑解决方案。
For others with the same problem; I used this compact solution that is easy to adjust.
您可以使用explode() 在每次出现“-”时分割字符串。 EG:
会给你留下:
因此,你想要的位将是中间带有“-”的前两项,因此我们可以从数组中弹出最后一个元素并加入其余元素:
这给出:
You could use explode() to split the string at each occurrence of "-". EG:
Would leave you with:
And as such the bit you want is going to be the first two items with a "-" in the middle, so we can pop the last element from the array and join the rest:
Which gives:
我发现正则表达式模式的控制和简洁对于这项任务来说是最有吸引力的。
匹配零个或多个非连字符,然后匹配一个连字符(N 次;本例中为 2 次),在最新的连字符匹配之前用
\K
重置完整字符串匹配,然后匹配其余字符。如果字符串中的连字符少于 N 个,则此方法不会删除任何字符。
代码:(Demo)
如果您想修剪第二个连字符后的尾随空格,您可以将其添加到模式中而不是对返回的字符串调用 rtrim() 。 (演示)
我个人不喜欢进行三个函数调用来生成临时数组的想法,然后只保留前两个元素,然后将数组重新连接为连字符分隔的字符串,但如果您非常讨厌正则表达式而想要这种方法,则应该将爆炸次数限制为 N+1,以便不会出现不必要的元素创建的。 (演示)
I find the control and brevity of a regex pattern to be most attractive for this task.
Match zero or more non-hyphens, then a hyphen (N amount of times; 2 in this case), resetting the full string match with
\K
before the latest hyphen matched, then match the remaining characters.This approach will not remove any characters if there are less then N hyphens in the string.
Code: (Demo)
If you want to trim trailing spaces after the second hyphen, you can add that to the pattern instead of calling
rtrim()
on the returned string. (Demo)I don't personally enjoy the idea of making three function calls to generate a temporary array, then only keep upto the first two elements, then re-joining the array to be a hyphen-delimited string, but if you hate regex so much to want that approach you should limit the number of explosions to be N+1 so that no unnecessary elements are created. (Demo)
strpos
substr
strpos
substr