开发者

using preg_match to strip specified underscore in php

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

apsd_01_03开发者_如何学编程s_somedescription apsd_02_04_somedescription

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

thanks.


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.


if you want to strip the "_somedescription" part:

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


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜