2

I have this array:

Array
(
    [count] => 12
    [6] => CN=G_Information_Services,CN=Users,DC=hccc,DC=campus
    [7] => CN=WEBadmin,CN=Users,DC=hccc,DC=campus
    [9] => CN=G_ISDept,CN=Users,DC=hccc,DC=campus
    [10] => CN=STAFF,CN=Users,DC=hccc,DC=campus
)

and I want to create an array of values that consist of the value between the first CN= and , of each array value below.

I probably will have to loop thru the array above, do a regex search for the first occurrence of cn and the value that follows it

I am not sure what I am doing wrong.

I need the final result to be an array that resembles this:

array('G_Information_Services', 'WEBadmin', 'G_ISDept', 'STAFF');

0

3 Answers 3

1

Use preg_match on each of the array values to get only the first corresponding CN value.

$found = array();

foreach ($arr AS $values) {
    if (preg_match('/CN=([^,]+),/',$values,$matches))
        $found[] = $matches[1];
}

Output

Array
(
    [0] => G_Information_Services
    [1] => WEBadmin
    [2] => G_ISDept
    [3] => STAFF
)
Sign up to request clarification or add additional context in comments.

Comments

1

Try this (not the most efficient way but it should work):

foreach ($array as $key => $value)
{
    if (is_numeric($key))
    {
        $array[$key] = explode(',', $array[$key]);
        $array[$key] = $array[$key][0];
        $array[$key] = substr($array[$key], 3);
    }
}

1 Comment

just realized I need to use a string search function to pull the appropriate value from the first occurrence of cn=
1

This gets the first value of CN= of each element of the array, it also ignores any DC= values.

$arr = array(
    'count' => 12,
    6 => 'CN=G_Information_Services,CN=Users,DC=hccc,DC=campus',
    7 => 'CN=WEBadmin,CN=Users,DC=hccc,DC=campus',
    9 => 'CN=G_ISDept,CN=Users,DC=hccc,DC=campus',
    10 => 'CN=STAFF,CN=Users,DC=hccc,DC=campus'
);

$newArr = array();

foreach($arr as $key => $value)
{
    if($key != 'count')
    {
        $temp = explode(',', $value);

        foreach($temp as $item)
        {
            if(strpos($item, 'CN=') === 0)
            {
                $item = substr($item, 3 );
                $newArr[] = $item;
                break 1;
            }
        }
    }
}

print_r($newArr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.