(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_explode_dnРазделить DN на его составные части


ldap_explode_dn(string $dn, int $with_attrib): array|false

Разделяет DN, возвращённый функцией ldap_get_dn(), и разбивает его на составные части. Каждая часть известна как относительное отличительное имя или RDN.

Список параметров


Отличительное имя объекта LDAP.


Используется для запроса, если RDNs возвращены только со значениями или также с их атрибутами. Для получения RDNs с атрибутами (то есть в формате attribute=value) установите параметр with_attrib в 0 и для получения только значений установите его в 1.

Возвращаемые значения

Возвращает массив всех компонентов DN или false, если возникла ошибка. У первого элемента в этом массиве есть ключ count, и он представляет собой число возвращённых значений. Следующие элементы - это компоненты DN с цифровыми индексами.

add a note

User Contributed Notes 6 notes

eero at eero dot info
7 years ago
I was converting LDAP related code to PHP7 which doesn't support /e modifier with preg_replace anymore, but instead you should use preg_replace_callback. This might help someone working on the same thing:


= 'Universität';

# < PHP7 compatible code
echo preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);

# >= PHP7 compatible code
echo preg_replace_callback('/\\\([0-9A-Fa-f]{2})/', function ($matches) { return chr(hexdec($matches[1])); }, $value);
gabriel at hrz dot uni-marburg dot de
20 years ago
Keep attention on UTF8 encoded DNs. Since openLDAP >=2.1.2
ldap_explode_dn turns unprintable chars (in the ASCII sense, UTF8
encoded) into \<hexcode>.


$dn="ou=Universität ,c=DE";


array(3) {
string(19) "ou=Universit\C3\A4t"
string(4) "c=DE"

Unfortunately, PHP don't support the ldap functions ldap_str2dn and
ldap_dn2str, but by means of preg_replace a workaround is possible to
recover the old behaviour of ldap_explode_dn

// workaround
function myldap_explode_dn($dn,$with_attribute){

$result=ldap_explode_dn ($dn, $with_attrib);
//translate hex code into ascii again
foreach($result as $key=>$value){
$result[$key]=preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);

//then follows for the example

$dn="ou=Universität ,c=DE";


array(3) {
string(15) "ou=Universität"
string(4) "c=DE"
hello+php at NOSPAM dot renoirboulanger dot com
11 years ago
I came accros this page and enjoyed the comments.

Since a LDAP string can sometimes be lengthy and have many attributes, I needed to be able to sort through all that is in.

In my case, I needed to get the subdomain part and other parameters.

Here is how I built my method.
* Parse, and format a DN string to Array
* Read a LDAP DN, and return an array keys
* listing all similar attributes.
* Also takes care of the character escape and unescape
* Example:
* CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com
* Would normally return:
* Array (
* [count] => 9
* [0] => CN=username
* [1] => OU=UNITNAME
* [2] => OU=Region
* [5] => OU=Country
* [6] => DC=subdomain
* [7] => DC=domain
* [8] => DC=com
* )
* Returns instead a manageable array:
* array (
* [CN] => array( username )
* [OU] => array( UNITNAME, Region, Country )
* [DC] => array ( subdomain, domain, com )
* )
* @author gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27 (part of the character replacement)
* @author Renoir Boulanger
* @param string $dn The DN
* @return array
function parseLdapDn($dn)
$parsr=ldap_explode_dn($dn, 0);
//$parsr[] = 'EE=Sôme Krazï string';
//$parsr[] = 'AndBogusOne';
$out = array();
$parsr as $key=>$value){
FALSE !== strstr($value, '=')){
$prefix,$data) = explode("=",$value);
$data=preg_replace("/\\\\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\\\1')).''", $data);
$current_prefix) && $prefix == $current_prefix){
$out[$prefix][] = $data;
} else {
$current_prefix = $prefix;
$out[$prefix][] = $data;
6 years ago
Probably not the best way but for those who are looking for a way to get de CN of a DN without the "cn=" part this is a function with a regex pattern:

function getCNofDN($dn) {


// Will print "emepese"

DavidSmith at byu dot net
20 years ago
[ Editor's Note: The segfault has been fixed and will not occur in PHP 4.3.4 or PHP 5.0.0 when they are released. However, it is still important to escape special characters as detailed below. ]

If your DN contains < or > characters, you must escape them with a backslash or ldap_explode_dn() will give you a "wrong parameter count" error or even a segmentation fault.

For example, these calls will fail with a "wrong parameter count" or a seg fault:

ldap_explode_dn( "cn=<bob>,dc=example,dc=com", 0 );
ldap_explode_dn( 'cn=<bob>,dc=example,dc=com', 0 );

But this will succeed

ldap_explode_dn( "cn=\<bob\>,dc=example,dc=com", 0 );

Notice also that the < and > are escaped with hex codes as noted above. This function is a nice wrapper that properly formats all DNs and can safely be called with < and > characters, and UTF-8 characters:

function my_explode_dn( $dn, $with_attributes=0 )
$dn = addcslashes( $dn, "<>" );
$result = ldap_explode_dn( $dn, $with_attributes );
//translate hex code into ascii again
foreach( $result as $key => $value )
$result[$key] = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
return $result;

I am using php 4.3.1. Good luck!
bs at muekno dot de
22 years ago
Copying is much better than typing!!!!
Just modify the constants.
Best wishes (and thanX 4 this helpfull site),
Bernd Schwaegerl
Mueller-Knoche GmbH, Systemhaus fuer EDV-Loesungen

# Example:

$HOST = "Yourhostname";
$USER_DN = "Yourldapuser_dn";
$PWD = "Ldapuserpassword";
$BASE_DN = "o=Your_organisation";



To Top