I defined a command to draw a box around a text and, optionally, put another character inside this box.
The command is this (along with MWE):
\documentclass{minimal}
\newlength{\xboxh} % Sets a macro for the height
\newlength{\xboxw} % and for the width
\newcommand{\putbox}[2][]{
\settoheight{\xboxh}{#2}% Gets the height
\settowidth{\xboxw}{#2}% and width of the input
\frame{\phantom{\rule{\xboxw}{\xboxh}}}% And draws a frame around it
\setbox0=\hbox{#1\unskip}\ifdim\wd0=0pt% And if the optional argument is not empty
\relax
\else
\hspace{-\xboxw}#1% Prints it too
\fi\relax
}
\begin{document}
Some text to \putbox{Z} fill up space \par
Some text to \putbox[Z]{Z} fill up space \par
Some text to \(\putbox{Z}\) fill up space
Some text to \(\putbox[Z]{Z}\) fill up space
\end{document}
The command is supposed to have the same behavior in text and math mode. But that's not what happens. When used in text mode the command outputs an unwanted space before and after the box, and also misplaces the content of the box (if any):
How do I fix the spacing issue with the command?