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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)