PHP - Help with str_replace

Posted on 2011-05-03
Last Modified: 2012-05-11
Hi, trying to use the following PHP code to replace a specific string in a variable with the contents of another variable. However the contents returned are blank.

$strYear = date("Y");
$strPageBaseText = str_replace("xxxYEARxxx", $strYear, $strPageBaseText);

Open in new window

If I change the code to use a fixed string rather than a variable, all is well.

$strPageBaseText = str_replace("xxxYEARxxx", "2011", $strPageBaseText);

Open in new window

Can anyone please tell me how to use str-replace to replace content based upon a variable rather than a fixed string.
Question by:Sean Clarke
    LVL 27

    Accepted Solution

    This works

    $strPageBaseText = "xxxxxxxxxxxxYEARxxxxxxxxxxxxx";
    $strYear = date("Y");
    $strPageBaseText = str_replace("xxxYEARxxx", $strYear, $strPageBaseText);
    echo "$strPageBaseText";

    Open in new window

    LVL 27

    Expert Comment

    by:Lukasz Chmielewski
    Do you want to replace this:
    LVL 82

    Expert Comment

    >>$strPageBaseText = str_replace("xxxYEARxxx", $strYear, $strPageBaseText);
    you will get a blank result if the right-most $strPageBaseText is initially blank. Make sure it is not blank BEFORE you attempt to do the replacing.

    as for "how to use str_replace()", you are using it correctly.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now