[Tex/LaTex] How to replace text

macros

I'd like to write something like this:

\replace{Text should be replaced here, here and here}{here}{Latex}

It should output

Text should be replaced Latex, Latex and Latex

How can this be done?

Best Answer

A complex solution that only replaces complete words:

\documentclass{article}
\usepackage{xparse,l3regex}

\ExplSyntaxOn
\NewDocumentCommand{\replace}{mmm}
 {
  \marian_replace:nnn {#1} {#2} {#3}
 }

\tl_new:N \l_marian_input_text_tl
\tl_new:N \l_marian_search_tl
\tl_new:N \l_marian_replace_tl

\cs_new_protected:Npn \marian_replace:nnn #1 #2 #3
 {
  \tl_set:Nn \l_marian_input_text_tl { #1 }
  \tl_set:Nn \l_marian_search_tl { #2 }
  \tl_set:Nn \l_marian_replace_tl { #3 }
  \regex_replace_all:nnN { \b\u{l_marian_search_tl}\b } { \u{l_marian_replace_tl} } \l_marian_input_text_tl
  \tl_use:N \l_marian_input_text_tl
 }
\ExplSyntaxOff

\begin{document}

\replace{Text should be replaced here, here and here}{here}{\LaTeX{}}

\replace{Text should be replaced here, here and not there}{here}{\LaTeX{}}

\end{document}

enter image description here

A simpler solution that replaces all occurrences:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\replace}{mmm}
 {
  \marian_replace:nnn {#1} {#2} {#3}
 }

\tl_new:N \l_marian_input_text_tl

\cs_new_protected:Npn \marian_replace:nnn #1 #2 #3
 {
  \tl_set:Nn \l_marian_input_text_tl { #1 }
  \tl_replace_all:Nnn \l_marian_input_text_tl { #2 } { #3 }
  \tl_use:N \l_marian_input_text_tl
 }
\ExplSyntaxOff

\begin{document}

\replace{Text should be replaced here, here and here}{here}{\LaTeX{}}

\replace{Text should be replaced here, here and not there}{here}{\LaTeX{}}

\end{document}

enter image description here