【问题标题】:Php Replace In String Except Between DelimitersPHP替换字符串中的分隔符之间除外
【发布时间】:2013-06-29 16:04:42
【问题描述】:

我正在制作一个 php 工具来自动创建并正确编码 mailto 链接。

我已经让它对一般文本正常工作,但我需要能够在自定义分隔符之间包含代码,这些代码将被 HTML 电子邮件模板创建程序拾取。

程序分隔符是。

这是我当前的代码:

$link = "mailto:unsubscribe@example.com?&subject=Unsubscribe&body=Dear \r\n请将我从你的邮件列表中删除。\r\nRef: ";
$link = str_replace(" ", "%20", $link);
$link = str_replace("\r\n", "%0A", $link);

目前它会转换分隔符内的空格,我该如何阻止它这样做?

【问题讨论】:

    标签: php replace delimiter mailto


    【解决方案1】:

    也许,这不是最优雅的解决方案,但它确实有效。我正在通过分隔符拆分您的字符串,并使用简单的确定性有限状态机仅替换分隔符之外的字符串。

    <?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;
    

    打印:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2022-01-06
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      相关资源
      最近更新 更多