Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extracting odd or even character positions from a string 2

Status
Not open for further replies.

jimoblak

Instructor
Oct 23, 2001
3,620
US
Is there a simple way to extract 2 variables from a string where one variable includes the odd character positions and another variable includes the even character positions?

$input="abcdef";

$oddoutput should be "bdf" (positions 1,3,5)
$evenoutput should be "ace" (positions 0,2,4)

This example assumes the first position in a string is zero and zero is considered an even number.

- - picklefish - -
 
You can use a regular expression for that.
Code:
# $subject is the string
preg_match_all('/(\w)(\w)/',$subj,$myarr);
# $myarr[0] has the even chars
# $myarr[1] has the odd chars

This is a quick and elegant solution. Right now it looks for word characters.
If you want anykind of chars use either a character class or '.':
preg_match_all('/(.)(.)/',$subj,$myarr);
 
DRJ478:

Running PHP 4.3.2, I get somewhat different output from your example than what you describe:

Code:
Array
(
    [0] => Array
        (
            [0] => ab
            [1] => cd
            [2] => ef
        )
    [1] => Array
        (
            [0] => a
            [1] => c
            [2] => e
        )
    [2] => Array
        (
            [0] => b
            [1] => d
            [2] => f
        )
)

Also, it doesn't work for strings with odd-numbered lengths. At least the string "abcdefg" causes it to fail -- the character "g" isn't dealt with at all. Here's what $myarr looks like processing that string:

Code:
Array
(
    [0] => Array
        (
            [0] => ab
            [1] => cd
            [2] => ef
        )
    [1] => Array
        (
            [0] => a
            [1] => c
            [2] => e
        )
    [2] => Array
        (
            [0] => b
            [1] => d
            [2] => f
        )
)

Since today's theme is "modulus", here's another solution which is a little more straighforward. It depends for its function on the fact that a string may be referenced as an array of characters:

Code:
<?php
$foo = 'abcdefg';

$oddoutput = '';
$evenoutput = '';

for ($counter = 0; $counter < strlen($foo); $counter++)
{
	if ($counter % 2 == 0)
	{
		$evenoutput .= $foo[$counter];
	}
	else
	{
		$oddoutput .= $foo[$counter];
	}
}

print $evenoutput;
print '<br>';
print $oddoutput;
?>

Want the best answers? Ask the best questions: TANSTAAFL!!
 
sleipnir
I mistyped.

Correction:
Of course the resulting array has the pairs at offset [0].
The offsets 1 and 2 contain the extracted characters.

 
Not if the input string has an odd number of characters. If you hand the function the string &quot;abcdefg&quot;, the &quot;g&quot; doesn't seem to end up anywhere.

I point this out because jimoblak doesn't specify the string will aways be of even length.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
You are absolutely right.
The regexp needs another edit:
Code:
preg_match_all('/(.)(.){0,1}/',$subj,$myarr);
$evenStr = implode($myarr[1],'');
$oddStr  = strlen($subj)%2 == 0 ? implode($myarr[2],'') : trim(implode($myarr[2],''));

This should cover it as long as there are no spaces in the subject.
 
I was unknowingly tuned out from this conversation (email filters are preventing me from receiving tek-tip reply notices).

On my other post today I asked to determine if a string was odd or even in length. If it is odd, I am adding a character to make it even. So this is not an issue when applying the reg exp.

The post above seems to work - - possibly better than DRJ478 expected...

DRJ478 said &quot;This should cover it as long as there are no spaces in the subject.&quot;

Why so? I just ran it and it seems to handle spaces okay. Is DRJ478 smarter than he/she thinks? I came looking for help on silly strings but it appears the real problem is DRJ478's low self-esteem. [bigsmile]

Thank you both! I am working on an encryption/encoding script if you were curious why I needed to do such bizarre functions.

- - picklefish - -
 
The spaces would only be significant under following circumstances:

1. The subject is of even length.
2. The rightmost character is a space or an uneven number of spaces.

My function would take the spaces off since there is a 'trim' in the oddStr generating code.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top