douzhuang6321 2015-11-04 19:56
浏览 32
已采纳

更改字符串值

I'm trying to replace ^ to <span>. But, I failed. I tried with str_replace but don't work properly.

So, my original value is:

^ffcb4a Special reward of the territory war. Used to manufacture Rank IX gears. Don&#039;t lose this.

You can see, that have a color value, starts with ^ and I want to replace that for: '<span style=color"#ffcb4a">.

But with my str_replace, I got this:

<span style='color:#'ffcb4a Special reward of the territory war. Used to manufacture Rank IX gears. Don&#039;t lose this.

As u can see, it doesn't work.

$item_description = str_replace('^', "<span style='color:#'" . '', $item_description);
  • 写回答

1条回答 默认 最新

  • douquanjie9326 2015-11-04 20:05
    关注

    You'll need to use a regex for this.

    $item_description = '^ffcb4a Special reward of the territory war. Used to manufacture Rank IX gears. Don\'t lose this.';
    echo preg_replace('/\^(.*?)\h/', 
    '<span style="color:#$1">', 
    $item_description);
    

    Output:

    <span style="color:#ffcb4a">Special reward of the territory war. Used to manufacture Rank IX gears. Don't lose this.
    

    It also is unclear where you want the span to end..

    This regex captures everything between a ^ and the first horizontal white space.

    Regex101 Demo: https://regex101.com/r/bA4dC8/1

    You can't use the str_replace because you don't know where to close the span.

    If you wanted to pull the first 6 characters after ^ you could change

    (.*?)\h
    

    to

    (.{6})
    

    Which says any 6 characters.

    Example:

    $item_description = '^ffcb4a Special reward of the territory war. Used to manufacture Rank IX gears. Don\'t lose this.';
        echo preg_replace('/\^(.{6})/', 
        '<span style="color:#$1">', 
        $item_description);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度