dongleibeng5602 2014-04-26 18:31
浏览 58
已采纳

PHP:替换字符串中的变量值

I am pretty new to PHP and hope someone here can help me with this:

I have a variable string that looks like the following, containing either nothing OR a series of words, separated with comma and space.

Example:

item1, item2, item3

What would be the best / fastest way to replace the single items in this string by adding an img tag with the same item name as the source + remove the commas ?

The above example should then look as follows:

item1 <img src="item1.png" alt="" /> item2 <img src="item2.png" alt="" /> item3 <img src="item3.png" alt="" />

Many thanks for any help with this, Mike.

  • 写回答

2条回答 默认 最新

  • douxi4414 2014-04-26 18:39
    关注

    This can be done in a 1-liner, but since you're new to PHP, lets just make it clear.

    First split the string to get an array of the different items.

    $itemsStr = "item1, item2, item3";  // input string
    $items = explode(", ", $itemsStr);  // Gets an array of items
    

    Now traverse the items array and add the string for each item:

    foreach($items as $key => $val)
    {
        $items[$key] = $item . "<img src='$item.png' alt='' /> ";
    }
    
    $output = implode(" ", $items);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?