tags:

views:

96

answers:

4

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.

+2  A: 

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.

Gumbo
A: 

if you want to strip the "_somedescription" part:

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

matei
A: 

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.

Nick Presta
A: 

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

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