Re: Newbie: special characters in regex?

From: Date: Tue, 25 Sep 2007 16:03:35 +0000
Subject: Re: Newbie: special characters in regex?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-262458@lists.php.net to get a copy of this message
Zembower, Kevin wrote:
I'm trying to modify a string so that it can be used as a Distinguished Name in an LDAP operation. Distinguished Names must have special characters, such as (, ), / and \ escaped with a backslash. For instance, 'Kevin (Kev) Zembower, III" becomes 'Kevin \(Kev\) Zembower\, III'. I tried to do this in this statement: $entry['FirstName'] = preg_replace('/(\)|\(|\,|\/)/',`\\$1', $entry['FirstName']; But it gives me this error: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /var/www/centernet/htdocs/ldap_auth/conversion.php on line 89 Can anyone help me get this statement right? Also, this doesn't seem very readable or easily maintained. I read about using an array() as the pattern string, which might make the statement more readable. Can anyone show me how this would be done, and suggest other ways to make this statement more easily maintained?
preg_replace('/([\(\),]+)/', '\\\$1', $str) You don't need the pipes (OR) in the search pattern. By placing them in the square brackets they act as a set of characters to search for. The comma also does not require escaping. I suggest you create an escapeDN() or escapeLDAPStr() function so that you can alter the search pattern in one place if you need to. Oh, and i left out the escaped forward slash you had in your search pattern. Are you really expecting someone to have a forward slash in their name? If so, change it to: '/([\(\)\/,]+)/' brian

« previous php.general (#262458) next »