Page 1 of 1

How to return all text before first underscore

Posted: 02 Nov 2012 10:19
by kiwichick
Hi there, I'm trying to use regexreplace to get whatever text is before the first underscore. So, I want apple to be returned from apple_pear_banana_orange.

I have this:

Code: Select all

$a="<curbase>";
   $b = regexreplace($a, "(.+)\_(.*)", "$1"),,1;
   echo $b;

but it returns apple_pear_banana and I can't figure out how to use the non-greedy ? to make it stop at the first underscore instead of the last. Cheers.

Re: How to return all text before first underscore

Posted: 02 Nov 2012 10:27
by highend
(.+?)(?=_).*

Re: How to return all text before first underscore

Posted: 02 Nov 2012 16:51
by Stefan
Explanation:

* and + multiplier work greedy, so let follow an ? to match non-greedy.
And, the underscore is no regex metachar and must not be escaped by \


While highends will works too, here is an expression more to your used style:

Code: Select all

"(.+?)_(.*)", "$1"

".+?_" means:

"." match one single occurrence of any sign,
"+" one-or-more of the expression just before,
"?" non-greedy till first occurrence of following expression,
"_" till an underscore.


.

Re: How to return all text before first underscore

Posted: 02 Nov 2012 19:59
by kiwichick
Thanks Stefan, I can't actually make highend's one work but yours is perfect!! And thanks for writing it more to my used style and for the explanation :biggrin: