14.7.1 Dynamic Replace Strings

Sometimes a constant replace string isn't enough. The replace text may vary depending on the context of the search hit. Even the special replace characters available in <sandr> like \1 may not be enough. In such situations we want complete control over what the replace text is, at every instance. We can use <fmtcp SANDCALL> for this.

Let's say we have a chunk of text that contains some double-quoted sections. We want to print this in HTML, and turn the double-quoted sections into bold. Simple: replace quote, text, quote with open-bold-tag, text, close-bold-tag. An astute REX user can accomplish this with a single <sandr> :


  <sandr '>>"=!"*"' "<B>\2</B>" $text>

But that assumes all the sections are properly double-quoted. We have human-written text, so of course it's inconsistent. Some sections are quoted with pairs of single-quotes instead, or a pair of backquotes, or even various combinations.

Writing <sandr> expressions to cover all these possibilities is cumbersome. All we really need to know is whether each match is a start or end quote. With <fmtcp SANDCALL> we can keep track of this:

(Run this example.    Download the source.)


  <SCRIPT LANGUAGE=vortex>
     
  <A NAME=main PUBLIC>
    <FORM METHOD=post ACTION=$url/markup.html>
      Enter text with double-quoted sections:<BR>
      <TEXTAREA NAME=text ROWS=5 COLS=60>$text</TEXTAREA><BR>
      <INPUT TYPE=submit>
    </FORM>
  </A>
  
  <A NAME=markup PUBLIC>
    <main>
    <P>Formatted text:<P>
    <$search = '"' "''" "``">
    <fmtcp SANDCALL $search boldit>
    <sb><PRE>$text</PRE></sb>
  </A>
  
  <A NAME=boldit PRIVATE>
    <IF $inq eq "y"></B><$inq = "n"><ELSE><B><$inq = "y"></IF>
  </A>
  
  </SCRIPT>

In our example, we accept the raw text from the user with a form and submit it to the <markup> function.

In <markup> , we use <fmtcp nbsp;SANDCALL> to search for all the possible start and end quote strings. For each, instead of a constant replace string, we call the function <boldit> to print the replace string. Then we start markup with <sb> as before.

The <boldit> function will get called for each quote string in $tex t. We print either an open or close bold tag to replace it. Which one depends on the state of the $inq variable: if y , we're currently inside a quoted section, so we end it with a close tag. Otherwise, we're outside a quoted section, so we start one with an open tag.

Let's run our example with some text (next page):

Back: In-line Search and Replace Next: Dynamic Replace Strings - Continued
Copyright © 2024 Thunderstone Software LLC. All rights reserved.