douci4026 2013-06-29 16:04
浏览 31

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?

  • 写回答

1条回答 默认 最新

  • duan198811 2013-06-29 17:25
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失