开发者

Combine Arrays and update a string with values

I have two issues I was hoping to get help on:

  1. Combine two arrays into one string and add some formatting
  2. ins开发者_运维百科ert the new string into a specific spot in a bigger string.

I have two arrays:

$array_1 =  array("100","200","300");
$array_2 = array("abc","def","ghi");

$result = array_merge($array_1, $array_2);

foreach ($result as $val){
//NEED HELP HERE  create a string that adds a "mac=" to the beginning of the current $val and adds a "/n" to the end of the current value.
}

The above should somehow create the string below:

 $my_string = "mac=100/n
              mac=200/n
              mac=300/n
               mac=abc/n
              mac=def/n
              mac=ghi/n";

Now for Part #2

I have a current string that was created already:

$current_String = "[MACS]/n
                   mac=blah1/n
                   mac=blah2/n
                   mac=blah3/n
                   [SERVICES]";

My last issue is to replace everything between [MACS]/n and [SERVICES] with $my_string

So I should end up with:

$updated_String = "[MACS]/n
                  mac=100/n
                  mac=200/n
                  mac=300/n
                  mac=abc/n
                  mac=def/n
                  mac=ghi/n
                  [SERVICES]";

Any help or insight would be greatly appreciated.


This should work:

$array_1 =  array("100","200","300");
$array_2 = array("abc","def","ghi");

$result = array_merge($array_1, $array_2);

$myString = "[MACS]/n\nmac=" . implode($result, "/n\nmac=") . "/n\n[SERVICES]";

//replace in other string
$macsIndex = strrpos($currentString, "[MACS]");
$servicesIndex = strrpos($currentString, "[SERVICES]");
$currentString = substr($currentString, 0, $macsIndex) . $myString . substr($currentString, servicesIndex+10);

Outputs:

[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]


$formatted = '';
foreach ($result as $val){
    $val = sprintf("mac=%s\n", $val);
    $formatted .= $val;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜