[Tex/LaTex] Avoiding math mode inside a lstlisting

listingsmath-modesymbols

I'm using listings to highlight some PHP code. My problems comes when the code to insert contains the '$' symbol, for example:

\begin{lstlisting}[style=PHP]
Select * FROM users WHERE user_name = $_POST['user'];
\end{lstlisting}

The $ set maths mode and the text after the lstlisting is included until I type another $. I've been looking for solution but unluckily. Using '\$' to escape the symbol $ does not work inside the lstlisting (in my pdf it would appear '\$' and obviously I don't want that to happen).

The PHP lst style is set like follows:

\lstdefinestyle{PHP}{
 frame=tb, to wrap the text with black horizontal lines
 language=php,
 aboveskip=3mm,
 belowskip=3mm,
 showstringspaces=false,
 basicstyle      = \small\ttfamily,
 keywordstyle    = \color{cyan},
 stringstyle     = \color{gray},
 identifierstyle = \color{blue},
 commentstyle    = \color{green},
 emph            =[1]{php},
 emphstyle       =[1]\color{black},
 emph            =[2]{if,and,or,else},
 breaklines=true,
 breakatwhitespace=true,
 tabsize=3,
 %emphstyle       =[2]\color{dkyellow}
}

Best Answer

If you're using TeXnicCenter, and it's only the coloring inside the editor:

This is a listed bug.

The issue also effects the verbatim environment: http://sourceforge.net/p/texniccenter/bugs/318/.

A "not really nice workaround": if it is really annoying (pages of code colored in a wrong way) you can put this after a wrong verbatim or listing environment: \ifx{\verb+$+}!\fi. It can help when you really need the coloring to be right.