用行替换字符串变量.将此字符串包含在其他变量中


Replace a string variable by line contains this string in other variable

我有一个包含很长列表的变量,这个列表的每一行都是唯一的,例如:

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

我有foreach脚本,我想将$variable中的单词替换为上面列表中的完整链接:

$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"

我该怎么做?

我想把$list改成一个数组,并将每个数组值与$variable进行比较,但当我有很多变量要替换时,这不是一个很好的解决方案。

您必须在新行上explode您的列表(PHP_EOL)才能获得URL数组,然后检查变量是否是任何URL的子字符串(使用strpos):

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

输出:

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

此代码将返回与变量匹配的第一个URL。如果您想要最后一个break,请删除它,或者使用数组存储找到的任何相应URL。