-1

I was wondering... I have two strings :

"CN=CMPPDepartemental_Direction,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan",
"CN=CMPPDepartemental_Secretariat,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan"

Is there a way in php to select only the first part of these strings ? I would like to just select CMPPDepartemental_Direction and CMPPDepartemental_Secretariat.

I had thought of trying with substr() or trim() but without success.

elieeee
  • 17
  • 7
  • 2
    You have to use a regex to extract string inside `***` – executable May 03 '22 at 09:43
  • @elieeee simpler / more direct regex: https://3v4l.org/iddDI – mickmackusa May 03 '22 at 12:07
  • You can also modify your string to resemble a url's querystring and parse the whole string into an associative array. https://3v4l.org/0hekm This works well on your sample input, but might not work well in other scenarios. – mickmackusa May 03 '22 at 12:12

2 Answers2

2

You should use preg_match with regex CN=(\w+_\w+) to extract needed parts:

$strs = [
    "CN=CMPPDepartemental_Direction,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan",
    "CN=CMPPDepartemental_Secretariat,OU=1 - Groupes de sécurité,OU=CMPP_Departementale,OU=Pole_Ambulatoire,OU=Utilisateurs_ADEI,DC=doadei,DC=wan"
];

foreach ($strs as $str) {
    $matches = null;

    preg_match('/CN=(\w+_\w+)/', $str, $matches);

    echo $matches[1];
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

If the strings always have the same structure, I recommend using a custom function find_by_keyword - so you can search for other keywords too.

function find_by_keyword( $string, $keyword ) {
    $array = explode(",",$string);
    $found = [];
    // Loop through each item and check for a match.
    foreach ( $array as $string ) {
        // If found somewhere inside the string, add.
        if ( strpos( $string, $keyword ) !== false ) {
            $found[] = substr($string, strlen($keyword));
        }
    }
    return $found;
}

var_dump(find_by_keyword($str2, "CN=")); 

// array(1) {
  [0]=>
  string(27) "CMPPDepartemental_Direction"
}

var_dump(find_by_keyword($str2, "OU="));
//array(4) {
  [0]=>
  string(25) "1 - Groupes de sécurité"
  [1]=>
  string(4) "CMPP"
  [2]=>
  string(4) "Pole"
  [3]=>
  string(12) "Utilisateurs"
}

Examle here.

toffler
  • 1,231
  • 10
  • 27