使用 preg_match 去除 php 中指定的下划线

发布于 2024-08-29 01:07:15 字数 200 浏览 4 评论 0原文

php 中的 preg_match 一直存在混淆。 我有一个像这样的字符串:

apsd_01_03s_somedescription apsd_02_04_somedescription

我可以使用 preg_match 删除第三个下划线(包括第三个下划线)中的任何内容吗?

谢谢。

There has always been a confusion with preg_match in php.
I have a string like this:

apsd_01_03s_somedescription
apsd_02_04_somedescription

Can I use preg_match to strip off anything from 3rd underscore including the 3rd underscore.

thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏花。依旧 2024-09-05 01:07:15

试试这个:

preg_replace('/^([^_]*_[^_]*_[^_]*).*/', '$1', $str)

这将只采用由 _ 分隔的前三个序列。因此从第三个 _ 开始的所有内容都将被删除。

Try this:

preg_replace('/^([^_]*_[^_]*_[^_]*).*/', '$1', $str)

This will take only the first three sequences that are separated by _. So everything from the third _ on will be removed.

日裸衫吸 2024-09-05 01:07:15

如果你想删除“_somedescription”部分:

 preg_replace('/([^]*)([^]*)([^]*)(.*)/', '$1_$2_$3', $str);

if you want to strip the "_somedescription" part:

 preg_replace('/([^]*)([^]*)([^]*)(.*)/', '$1_$2_$3', $str);

十级心震 2024-09-05 01:07:15

我同意 Gumbo 的答案,但是,您可以使用 PHP 的数组函数,而不是使用正则表达式:

$s = "apsd_01_03s_somedescription";

$parts = explode("_", $s);
echo implode("_", array_slice($parts, 0, 3));
// apsd_01_03s

与正则表达式解决方案相比,此方法的执行速度似乎相似。

I agree with Gumbo's answer, however, instead of using regular expressions, you can use PHP's array functions:

$s = "apsd_01_03s_somedescription";

$parts = explode("_", $s);
echo implode("_", array_slice($parts, 0, 3));
// apsd_01_03s

This method appears to execute similarly in speed, compared to a regular expression solution.

仅一夜美梦 2024-09-05 01:07:15

如果第三个下划线是最后一个,您可以这样做:

preg_replace('/^(.+)_.+?)$/', $1, $str);

If the third underscore is the last one, you can do this:

preg_replace('/^(.+)_.+?)$/', $1, $str);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文