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.

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

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害