stripping sections of a string out...

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Frozenlight777
Forum Commoner
Posts: 75
Joined: Wed May 28, 2008 12:59 pm

stripping sections of a string out...

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: stripping sections of a string out...

Post by VladSun »

There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Frozenlight777
Forum Commoner
Posts: 75
Joined: Wed May 28, 2008 12:59 pm

Re: stripping sections of a string out...

Post by Frozenlight777 »

sweet. That's what I was looking for.
User avatar
Frozenlight777
Forum Commoner
Posts: 75
Joined: Wed May 28, 2008 12:59 pm

Re: stripping sections of a string out...

Post 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;
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: stripping sections of a string out...

Post 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;
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Frozenlight777
Forum Commoner
Posts: 75
Joined: Wed May 28, 2008 12:59 pm

Re: stripping sections of a string out...

Post by Frozenlight777 »

Very true. Thanks!
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: stripping sections of a string out...

Post 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";
; )
Post Reply