str_replace only replaces the second array

Asked

Viewed 47 times

0

Hello,

I have a problem that I’ve tried to fix in many ways, but I can’t! I’ve searched the function str_replace() in the php.net and nothing!

I have the following code:

$cod = '192.168.1.1';
$char = '300';

$arrayFind = array('[cod]', '[char]');
$arrayReplace = array($cod, $char);

for($i = 0; $i < count($arrayFind); $i++) {
$response = str_replace($arrayFind[$i], $arrayReplace[$i], '[cod]/[char]');
}

The str_replace() only replaces the [char], I’m new to PHP and I like it a lot, but I’m very confused now!

  • One problem is that the variable $response is lost there in the middle without interaction. But, already tried it $arrayFind = array('[cod]', '[char]'); $arrayReplace = array($cod, $char); echo str_replace($arrayFind, $arrayReplace, '[cod]/[char]'); ?

  • Yes! I have tried several forms, etc.. and none worked! So I had to ask a question aq at Sopt :/

  • What is in the variable $cod and $char ?

  • Could be anything.. $cod = '123'; $char = 'abc';

  • is that already thought that it can be passing anything wrong ? instead of a string, an array ?

  • Well, if that’s the case, here’s to me: $cod = '192.168.1.1'; $char = '300';

  • 1

    Click here and see the stdout.

  • Oops thanks! It worked right here! I will try to know more ;)

  • 1

    It would be nice, when asked, to enter what you want to get as an answer and what is being obtained. That way you’ll make it clearer what you’re trying to do.

Show 4 more comments

1 answer

1

<?php

$cod = '192.168.1.1';
$char = '300';

$arrayFind = array('[cod]', '[char]');
$arrayReplace = array($cod, $char);

$response = str_replace($arrayFind, $arrayReplace, '[cod]/[char]');

//$response = 192.168.1.1/300
  • 2

    Explain your answer a little more to help other people as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.