dnc123
dnc123

Reputation: 141

Does str_replace() affect the subject string by reference?

I got this code here:

<?php 
include_once("php_includes/loginLinks.php");
str_replace("member_profile","php_includes/member_profile",$loginLinks);
str_replace("member_account","php_includes/member_account",$loginLinks);
str_replace("logout","php_includes/logout",$loginLinks);
str_replace("register_form","php_includes/register_form",$loginLinks);
str_replace("login","php_includes/login",$loginLinks);
echo $loginLinks;
?>

It's supposed to change the root folder of links, I'm pretty sure there is some logic mistake in there.

How to change the links directories of newly echo'ed links directories to another directory, or is there another way to change it?

Upvotes: 0

Views: 116

Answers (2)

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

Your mistake is you didn't assign the replacement into the $loginLinks. But instead of str_replace() use of preg_replace() will be much better for your need I believe.

$loginLinks = preg_replace(
    "/(member_profile|member_account|logout|login|register_form)/",
    "php_includes/$1",
    $loginLinks
);

Upvotes: 2

Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16676

You must update the variable with the results of the str_replace operation like this:

<?php 
include_once("php_includes/loginLinks.php");
$loginLinks = str_replace("member_profile","php_includes/member_profile",$loginLinks);
$loginLinks = str_replace("member_account","php_includes/member_account",$loginLinks);
$loginLinks = str_replace("logout","php_includes/logout",$loginLinks);
$loginLinks = str_replace("register_form","php_includes/register_form",$loginLinks);
$loginLinks = str_replace("login","php_includes/login",$loginLinks);
echo $loginLinks;
?>

str_replace doesn't modify the original variable, but returns a new value. Here I update $loginLinks with the updated value.

Upvotes: 5

Related Questions