删除最后一个连字符后的字符串 [英] Remove string after last hyphen

查看:37
本文介绍了删除最后一个连字符后的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除字符串中的最后一个连字符及其后的任何内容.看了之后,我发现了第一个连字符但不是最后一个的东西:

I would like to remove the last hyphen and anything after it in a string. After looking I found something that does the first hyphen but not last:

$str = 'sdfsdf-sdfsdf-abcde';
$str = array_shift(explode('-', $str));

当前字符串

$str = 'sdfsdf-sdfsdf-abcde';

想要的结果

$str = 'sdfsdf-sdfsdf';

推荐答案

你可以使用这个preg_replace:

$repl = preg_replace('/-[^-]*$/', '', $str);
//=> sdfsdf-sdfsdf

-[^-]*$ 将匹配 - 后跟 0 个或多个非连字符在行尾.

-[^-]*$ will match - followed by 0 or more non-hyphen characters before end of line.

这篇关于删除最后一个连字符后的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆