substituting a specified text in a file

Posted on 2009-04-19
Last Modified: 2012-05-06
from a file modifer.php I need to modify another file index.php substituting the text:
<div id=change this>foobar</div>

with this new text:
<div id=change this>abcdefghi</div>

what are the PHP commands to do this?
Question by:lucavilla
    LVL 3

    Assisted Solution

    It str_replace

    e.g. from
    // Provides: <body text='black'>
    $bodytag = str_replace("%body%", "black", "<body text='%body%'>");

    you can also use $variable at the end instead of the <body ...
    LVL 13

    Accepted Solution


    $newWord = "adsasdads";
    $str = "<div id=change this>foobar</div>";
    $str = preg_replace('|(<div id=change this>)foobar(</div>)|', "$1$newWord$2", $str);

    Open in new window


    Author Comment

    marchent, what's the minimalist way to do the same?
    LVL 13

    Expert Comment

    don't know that.
    LVL 3

    Expert Comment

    it really depends on how much you know of the existing string. If the <div id=change this> and </div> is always the same marchents pretty much the shortest way.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to count occurrences of each item in an array.

    794 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

    17 Experts available now in Live!

    Get 1:1 Help Now