PHP & Regex : Replace entire <head>

Posted on 2009-04-22
Last Modified: 2012-05-06
I'm storing an entire html page in $html. I need to replace everything from <head> to </head> with my own $head (so either the stuff inside is replaced, or the stuff inside and the tags - whichever makes more sense). How can I do this?
Question by:level9wizard
    LVL 14

    Expert Comment

    LVL 6

    Expert Comment

    $html = preg_replace("|<head>(.*)</head>|m",$newhead,$html);
    LVL 6

    Accepted Solution

    or a little bit better:
    $html = '
    old head
    $newhead = "<head>testar</head>";
    $html = preg_replace('|<head>.*<\/head>|siu',$newhead,$html);
    echo $html;

    Open in new window


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    A colleague recently asked me about how to give his client a small part of the web site that could be completely under the client's control.  Since I have done this sort of thing before to add emergency banners to a web site, I decided I would creat…
    Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
    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 create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

    732 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