JPro
JPro

Reputation: 6556

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_03s_somedescription apsd_02_04_somedescription

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

thanks.

Upvotes: 0

Views: 1068

Answers (4)

Powerlord
Powerlord

Reputation: 88846

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

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

Upvotes: 0

Nick Presta
Nick Presta

Reputation: 28705

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.

Upvotes: 0

matei
matei

Reputation: 8705

if you want to strip the "_somedescription" part:

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

Upvotes: 0

Gumbo
Gumbo

Reputation: 655785

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.

Upvotes: 2

Related Questions