Kshitij Yelpale Kshitij Yelpale - 1 year ago 61
PHP Question

How to prevent some characters in trim function in php

I have a string in variable

$str = '"100 \""';

I want to use trim function to trim
(double quotes) character except the one after escape character.

$str = trim($str, '"');

But it is trimming all the double quotes,
So can anyone tell me how i can prevent that ?
Anyways i have written my own trim function for that, but want to use standard API function in php.

Answer Source

Very well, I'll bite. What you need to use is a negative lookbehind in a regular expression. The expression, in it's simplest form would look like this:



  • (?<!: Negative lookbehind. This means that you want to check that the expression is not preceded by a certain pattern:
  • \\): The lookbehind pattern. In this case, the pattern will only match if it's not preceded by a literal \.
  • ": A literal ". Again, because of the lookbehind, you won't match double quotes that are escaped.


In your case, you're probably looking for:

$str = preg_replace('/(?<!\\)"/', '', $str);

Replacing all " that are not escaped with an empty string (essentially removing them).

Because you're using trim, you might only want to remove leading and trailing quotes. In that case, you'll have to alter the expression just a tiny bit, and use this:



  • (?<!\\): same as before (negative lookbehind)
  • (^"|"$): still matching a literal ", but only if it's the start or the end of the string.

Of course, you don't really need the lookbehind for the leading quote, so this expression will work just as good (if not better):



  • ^": Matches the first character in the string if it is an unescaped ".
  • (?<!\\): same old negative Lookbehind
  • "$: Matches a double quote at the end of the string (only if it's not preceded by a \, as per negative lookbehind

Both of these regex's will allow you to process strings like this:

$str = '"foo"bar\""';
echo preg_replace('/(^"|(?<!\\)"$)/', '', $str);

output foo"bar\"

Demo II

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download