0

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

  1. Combine two arrays into one string and add some formatting
  2. insert 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.

2
  • I need a hamburger and a large coke. Commented Apr 19, 2011 at 20:15
  • 1
    Didn't mean to sound demanding. Commented Apr 19, 2011 at 20:27

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

OK this works perfect Thanks! But what if $current_String was part of a much bigger string? Can I find and replace [MACS] and everything in between to0 [SERVICES] with $myString is that possible?
0
$formatted = '';
foreach ($result as $val){
    $val = sprintf("mac=%s\n", $val);
    $formatted .= $val;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.