php multiple str_replace,只替换了第一个实例

时间:2013-09-12 19:00:02

标签: php

第一个str_replace工作正常,但以下两个不能处理。我测试了替换变量和替换字符串都存在/ echo。每个人都需要一个唯一的$body.吗?

        $body.= "--$mime_boundary\n";
        $body.= "Content-Type: text/html; charset=\"UTF-8\"\n";
        $body.= "Content-Transfer-Encoding: 7bit\n\n";    
        $body.= str_replace("%%user%%",$en['user'],$html_content);
        $body.= str_replace("%%confcode%%",$en['confcode'],$html_content);
        $body.= str_replace("%%memb_id%%",$en['memb_id'],$html_content);    
        $body.= "\n\n";
        $body.= "--$mime_boundary--\n";

3 个答案:

答案 0 :(得分:3)

尝试

    $body.= str_replace(
        array(
            "%%user%%",
            "%%confcode%%",
            "%%memb_id%%"
        ), 
        array(
            $en['user'],
            $en['confcode'],
            $en['memb_id']
        ),
        $html_content
    );

而不是

    $body.= str_replace("%%user%%",$en['user'],$html_content);
    $body.= str_replace("%%confcode%%",$en['confcode'],$html_content);
    $body.= str_replace("%%memb_id%%",$en['memb_id'],$html_content); 

答案 1 :(得分:1)

http://php.net/manual/en/function.str-replace.php

试试这个。如果您要替换之前未替换的值,我认为您可能会遇到一些问题。

$body.= "--$mime_boundary\n";
$body.= "Content-Type: text/html; charset=\"UTF-8\"\n";
$body.= "Content-Transfer-Encoding: 7bit\n\n";    
$body.= str_replace(array("%%user%%","%%confcode%%","%%memb_id%%"),array($en['user'],$en['confcode'],$en['memb_id']),$html_content);
$body.= "\n\n";
$body.= "--$mime_boundary--\n";

答案 2 :(得分:0)

我想,您想要在同一$html_content

中替换所有字符串

因此,您应该对已经处理的字符串调用replace,以使它们全部正常工作:

    $body.= "--$mime_boundary\n";
    $body.= "Content-Type: text/html; charset=\"UTF-8\"\n";
    $body.= "Content-Transfer-Encoding: 7bit\n\n";    
    $html_content= str_replace("%%user%%",$en['user'],$html_content);
    $html_content= str_replace("%%confcode%%",$en['confcode'],$html_content);
    $body.= str_replace("%%memb_id%%",$en['memb_id'],$html_content);    
    $body.= "\n\n";
    $body.= "--$mime_boundary--\n";

请注意,这会改变您的$html_content。如果不需要,可以使用另一个变量来分配结果,或者使用Mark Ba​​ker的解决方案。

相关问题