每次出现时用不同的值替换相同的字符串

时间:2019-04-17 08:51:18

标签: php

我试图用相同的字符串替换每次出现的不同值,但是我遇到了很大的麻烦,我不知道如何解决它。

$order = "john, book, 1";
$order = explode(',', $order);

$url = "https://fakerestapi.azurewebsites.net/api/author/{}/data/{}/oc/v/{}/";
$repeat =  substr_count($url, "{}");

for ($i=0; $i<=$repeat; $i++) {
    $final .= str_replace('{}', $repeat[$i], $url);
}

echo $final;

当前输出:

NOTICE Undefined variable: final on line number 10

https://fakerestapi.azurewebsites.net/api/author//data//oc/v/https://fakerestapi.azurewebsites.net/api/author//data//oc/v/https://fakerestapi.azurewebsites.net/api/author//data//oc/v/https://fakerestapi.azurewebsites.net/api/author//data//oc/v/

我的预期输出应该是这样的:

https://fakerestapi.azurewebsites.net/api/author/john/data/book/oc/v/1/

你能帮我吗? 谢谢

3 个答案:

答案 0 :(得分:0)

这将起作用

<?php

$order = "john, book, 1";
$order = explode(',', $order);


$url = "https://fakerestapi.azurewebsites.net/api/author/{}/data/{}/oc/v/{}/";
$repeat =  substr_count($url, "{}");

$final = $url;

for ($i=0; $i < $repeat; $i++) {
    $final = preg_replace('/{}/', $order[$i], $final, 1);
}

echo $final;

?>

答案 1 :(得分:0)

我假设您的$order数组只有三个值,

$order = "john, book, 1";
$order = explode(',', $order);

$url = "https://fakerestapi.azurewebsites.net/api/author/%s/data/%s/oc/v/%s/";

echo sprintf($url, trim($order[0]), trim($order[1]), trim($order[2]));

输出:

https://fakerestapi.azurewebsites.net/api/author/john/data/book/oc/v/1/

答案 2 :(得分:0)

使用爆炸使URL成为数组,然后将两个数组循环连接。

$order = "john, book, 1";
$order = explode(', ', $order);


$url = "https://fakerestapi.azurewebsites.net/api/author/{}/data/{}/oc/v/{}/";
$url = explode("{}", $url);
$final ="";

foreach($url as $key => $u){
    $final .= $u;
    if(isset($order[$key])) $final .= $order[$key];
}

echo $final;
//https://fakerestapi.azurewebsites.net/api/author/john/data/book/oc/v/1/
相关问题