Php替换字符串除了分隔符之外

I am making a php tool to automatically create and correctly encode mailto links.

I have got it working correctly for general text but I need to be able to include code between custom delimiters that will be picked up by an HTML email template creator program.

The programs delimiters are <% %>.

Here is my current code:

$link = "mailto:unsubscribe@example.com?&subject=Unsubscribe&body=Dear <% User.Name %> Please remove me from your mailing list. Ref: <% Customer.Ref %>";
$link = str_replace(" ", "%20", $link);
$link = str_replace(" ", "%0A", $link);

At the moment it will convert the spaces within the delimiters, how can I stop it doing this?

Maybe, not the most elegant solution, but it works. I am splitting your string by delimiters and using a simple deterministic finite state machine to replace only in strings outside of delimiters.

<?php
$link = "Dear <% User N a m e %>Please remove me";

function escape_outside_delimiters(&$string)
// {{{
{
    $output = "";
    //splitting the string by either <% or %>, keeping the delimiters
    $matches = preg_split("/(:?<%|%>)/", 
                         $string,
                         -1, 
                         PREG_SPLIT_DELIM_CAPTURE);

    //replacing everything outside delimiters, 
    //putting the escaped chunks to $output
    $n = count($matches);
    $flag = 0;
    for ($i = 0; $i < $n; ++$i)
    {
        switch ($matches[$i]){
        case "<%":
            $flag = 1;
            break;
        case "%>":
            $flag = 0;
            break;
        default:
            if ($flag == 0)
            {
                $matches[$i] = str_replace(" ", "%20", $matches[$i]);
            }
        }
        $output .= $matches[$i];
    }

    return $output;
}
// }}}


$link = escape_outside_delimiters($link);
print $link;

prints:

Dear%20<% User N a m e %>Please%20remove%20me