0

What is the correct form to make $id behave as a PHP variable inside the str_replace command? I've tried wrapping the $id inside with {, or ., but nothing helped. I'm not even sure how to define the problem I'm having here so I didn't really know how to Google this:

$id="Something";

$new = str_replace('?abc', '?id=$id&abc', $original);
rockyraw
  • 1,125
  • 2
  • 15
  • 36

2 Answers2

2

There are two ways to concatenate strings in PHP. In your example, it would be either:

$new = str_replace('?abc', '?id=' . $id . '&abc', $original);

or

$new = str_replace('?abc', "?id=$id&abc", $original);

Note that the first option is slightly more efficient, and the spaces are optional.

Andrew
  • 1,322
  • 14
  • 20
  • 1
    This won't work. As FirstOne stated *RTM: [strings-double quoted](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double). I suggest you to read it all...* – Script47 Dec 30 '15 at 22:56
  • 1
    `$new = str_replace('?abc', '?id=' . $id . '&abc', $original);` no quotes around the variable, else it will fail – Steve Dec 30 '15 at 22:57
  • Quotes around variables work if they are double quotes – Phiter Dec 30 '15 at 22:58
  • @PhiterFernandes I believe the issue is that the answer has single quotes around the variable. – Jonathan Kuhn Dec 30 '15 at 22:58
  • Mixing single and double quotes in your second example is no good. – Script47 Dec 30 '15 at 22:59
-1

i think it needs to be work like this.

$search = 's';
$replace = 'r';
$subject = 'subject';

$result = str_replace($search,$replace,$subject);

var_dump($result);

and the result will be 'rubject'.

Enes Tufekci
  • 85
  • 1
  • 6
  • 1
    [*What?*](http://previews.123rf.com/images/stuartphoto/stuartphoto1205/stuartphoto120500715/13564622-Puzzled-Confused-Lost-Signpost-Shows-Puzzling-Problem-Stock-Photo.jpg) – Script47 Dec 30 '15 at 23:06