dongzhugao9929 2014-09-16 08:44 采纳率: 0%
浏览 37
已采纳

逐行替换字符串变量在其他变量中包含此字符串

I have variable that contains very long list, each line of this list is unique, example:

$list = "http://example.com/xcvdre4a/our_trip-2014.jpg
http://example.com/awe38fd/weeding.jpg
http://example.com/ds543gfd/church.jpg"

I have foreach script where I would like to replace word from $variable into full link from the list above:

$variable = "church.jpg";
// use the word from $variable to find a link from $list and replace $variable.
echo $variable;
// should be "http://example.com/notsorted/church.jpg"

How can I do it?

I thought to change $list into an array and compare each array value to $variable, but it's not very good solution when I have many variables to replace.

  • 写回答

1条回答 默认 最新

  • dqj96395 2014-09-16 08:47
    关注

    You'll have to explode your list on new lines (PHP_EOL) to get an array of URL, then check if the variable is a sub-string of any URL (with strpos) :

    foreach (explode(PHP_EOL, $list) as $url) {
     if (strpos($url, $variable) !== false) {
      $variable = $url;
      break;
     }
    }
    
    echo $variable;
    

    Output :

    http://example.com/ds543gfd/church.jpg

    This code will return the first URL that match the variable. Remove the break if you want the last one instead, or use an array to store any corresponding URL you find.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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