shaweren
V2EX  ›  问与答

PHP str_replace 替换 $变量符号无法识别的问题

  •  
  •   shaweren · May 19, 2017 · 3258 views
    This topic created in 3471 days ago, the information mentioned may be changed or developed.

    $text="[%url][%title]
    "; $tex=str_replace("%","$",$text); echo $tex; str_replace 替换后变量不能识别怎么破

    14 replies  •  2017-05-20 03:33:12 +08:00
    explon
    explon
    May 19, 2017
    1
    单引号跟双引号的区别你知道吗?
    konakona
    konakona
    May 19, 2017
    2
    "\$" 试试看咯
    或者'$'
    shaweren
    shaweren
    OP
    May 19, 2017
    3
    @explon 单引号里面的变量不能识别?
    shaweren
    shaweren
    OP
    May 19, 2017
    4
    @konakona 好像没有用
    konakona
    konakona
    May 19, 2017
    5
    @shaweren 其实你的代码,我运行已经成功了。
    shaweren
    shaweren
    OP
    May 19, 2017
    6
    @konakona 输出是作为字符串输出了,而不是作为变量。
    kchum
    kchum
    May 19, 2017
    7
    是输出这个 [$url][$title] 运行没毛病,还是你需求不对
    shaweren
    shaweren
    OP
    May 19, 2017
    8
    @kchum
    @konakona

    $title="titleName";

    $url="http";

    $text="[%url]<I>[%title]</I><br>";

    $tex=str_replace('%','$',$text);

    echo $tex;

    希望输出是:[http]<I>[titleName]</I><br>;

    这个能实现么?
    U7Q5tLAex2FI0o0g
    U7Q5tLAex2FI0o0g
    May 19, 2017❤️1
    9
    <?php
    $url = 'urlurl';
    $title = 'titletitle';
    $a = '[%url][%title]';
    $b = str_replace('%', '$', $a);
    eval("\$b = \"$b\";");
    echo $b . PHP_EOL;
    shaweren
    shaweren
    OP
    May 19, 2017
    10
    @littleylv 膜拜!
    hteen
    hteen
    May 19, 2017❤️1
    11
    $url = 'url';
    $title = 'title';
    $text="[%url%][%title%]";
    preg_match_all('/%(\w+)%/', $text, $match);

    foreach ($match[1] as $key => $val)
    $text = str_replace($match[0][$key], $$val, $text);

    echo $text;
    kchum
    kchum
    May 19, 2017❤️1
    12
    @shaweren [$url]<I>[$title]</I><br> ,你的需求不是用这个。

    $title="titleName";
    $url="http";
    printf("[%s]<I>[%s]</I><br>" , $url,$title);

    输出
    [http]<I>[titleName]</I><br>
    wangjie
    wangjie
    May 19, 2017
    13
    @shaweren #8
    <?php
    $title = "titleName";
    $url = "http";
    $text = "[%url]<I>[%title]</I><br>";
    $tex = preg_replace_callback('/%([a-z]+)/', function($matches) {
    global ${$matches[1]};
    return ${$matches[1]};
    } , $text);
    echo $tex;
    msg7086
    msg7086
    May 20, 2017
    14
    $符号是在要写字符串的时候就确定下来的。
    你这代码,只有第一行写双引号的时候$才会被解析。
    没第二行以后的代码什么事的。
    解析$是双引号的功能。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   947 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 19:54 · PVG 03:54 · LAX 11:54 · JFK 14:54
    ♥ Do have faith in what you're doing.