PHP : How to select specific parts of a string

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.

>Solution :

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];
}

Leave a Reply