[Tex/LaTex] insert text in rule

rulestext;ulem

I have difficulty writing a compact command that allows me to insert a text between two lines.
I read some links such as this and this, but each one treats the left and right line separately

\documentclass{article}
\usepackage{amsmath} %<<=== 
\usepackage[normalem]{ulem}
\usepackage{xcolor}

\newcommand\gsout{\bgroup\markoverwith{\textcolor{gray}{\rule[0.5ex]{2pt}{2.5pt}}}\ULon}

\newcommand*{\sxrule}[1][3em]{\textcolor{gray}{\rule[0.5ex]{#1}{2.5pt}}\;}


\begin{document}

\sxrule Osservazioni \gsout{\hfill}

\end{document} 

enter image description here

Have any suggestions? thanks

Best Answer

Perhaps something like this:

enter image description here

Here's the code:

\documentclass{article}
\usepackage{xcolor}
\usepackage{lipsum}

\newlength\sxrulelength
\newcommand\sxrule[2][3em]{%
  \settowidth\sxrulelength{\,#2\,}%
  \noindent%
  \textcolor{gray}{\rule[0.5ex]{#1}{2.5pt}}\,#2\,%
  \textcolor{gray}{\rule[0.5ex]{\dimexpr\linewidth-\sxrulelength-#1\relax}{2.5pt}}%
}

\begin{document}

  \lipsum

  \sxrule{Osservazioni}

  \lipsum

\end{document}

The \sxrule macro has an optional argument that controls the length of the "left hand" line. As in the OP, this defaults to 3em.

Judging from the comments, perhaps the definition

\newcommand\sxrule[2][3em]{%
  \settowidth\sxrulelength{\,#2\,}%
  \noindent%
  \textcolor{gray}{\rule[0.5ex]{#1}{2.5pt}}\,\textbf{#2}\,%
  \textcolor{gray}{\rule[0.5ex]{\dimexpr\linewidth-\sxrulelength-#1\relax}{2.5pt}}%
}

is better as now \sxrule{Osservazioni} puts "Osservazioni" in bold:

enter image description here