代码之家  ›  专栏  ›  技术社区  ›  JBstar

str_替换为特殊角色场景

  •  1
  • JBstar  · 技术社区  · 6 年前

    我有一个奇怪的场景,如果我使用下面的代码,任何帮助都将不胜感激,我正在尝试在标题上添加h1标记

    $phrase  = "*title** Some text goes here.";
    $target = ['*', '**'];
    $replace   = ["<h1>", "</h1>"];
    
    $newPhrase = str_replace($target, $replace, $phrase);
    
    echo $newPhrase;
    

    输出的HTML如下所示:

    <h1>title</h1>
    <h1></h1>
    <h1> Some text goes here.</h1>
    

    但如果我使用以下内容(与之前相同,但*替换为1,**替换为2):

    $phrase  = "1title2 Some text goes here.";
    $target = ['1', '2'];
    $replace   = ["<h1>", "</h1>"];
    
    $newPhrase = str_replace($target, $replace, $phrase);
    
    echo $newPhrase;
    

    它起作用了,我得到了输出:

     <h1>title</h1>
     Some text goes here. (not as a H1 element)
    

    谁能解释一下吗?为什么要这样对待*角色?我能解决这个问题,这样我就能使用它们了吗?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  2
  •   user3783243    6 年前

    你的 ** 从不匹配,因为单身 * 匹配每一个事件。改变顺序,这样你就可以先换双色的了。

    <?php
    $phrase  = "*title** Some text goes here.";
    $target = ['**', '*'];
    $replace   = ["</h1>", "<h1>"];
    
    $newPhrase = str_replace($target, $replace, $phrase);
    
    echo $newPhrase;
    

    https://3v4l.org/21HZv

    如果你使用 1 11 。另外,你发布的HTML不是PHP生成的。我认为你的浏览器正在自动更正这一点。