I have a string in variable
$str = '"100 \""';
$str = trim($str, '"');
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);
" 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);