Page 1 of 1

stripping sections of a string out...

Posted: Fri Jun 06, 2008 9:35 am
by Frozenlight777
Blah, when it comes to regular expressions i'm completely lost.

$value = "CN0G554F641808470REL"

$value is in a loop so the string itself changes frequently, except for the length. $value will always contain 20 characters.
What i'd like to do is have a new variable:

$value2 = "G554F8470REL"

What needs to be done is stripping the first 3 characters, keeping the next 5, stripping the next 5 then keeping the rest.
Something like CN0G554F641808470REL stripping out the colored text.

I have no idea where to begin.

Re: stripping sections of a string out...

Posted: Fri Jun 06, 2008 9:43 am
by VladSun

Re: stripping sections of a string out...

Posted: Fri Jun 06, 2008 9:44 am
by Frozenlight777
sweet. That's what I was looking for.

Re: stripping sections of a string out...

Posted: Fri Jun 06, 2008 9:57 am
by Frozenlight777
Perfect. Thanks for the link...

Ended up writing this to make it work

Code: Select all

    $input = "CN0G554F641808470REL";
    $value = substr($input, -7);
    $value2 = substr($input, 3, -12);
    echo $value2 . $value;

Re: stripping sections of a string out...

Posted: Fri Jun 06, 2008 10:00 am
by VladSun
:) You're welcome :)

You may write it in a more compact way (in case you don't need the value1 and value2 been separated):

Code: Select all

$input = "CN0G554F641808470REL";
$value = substr($input, 3, -12) . substr($input, -7);
echo $value;

Re: stripping sections of a string out...

Posted: Fri Jun 06, 2008 10:01 am
by Frozenlight777
Very true. Thanks!

Re: stripping sections of a string out...

Posted: Fri Jun 06, 2008 11:13 am
by prometheuzz
I agree that substr(...) is more appropriate to use instead of regex, but since this is the regex section of this forum (and I like regexes!), here's a regex approach:

Code: Select all

$tests = "CN0G554F641808470REL";
echo preg_replace('/^.{3}(.{5}).{5}(.*)$/', '$1$2', $tests) . "\n";
; )