Regular Expressions & preg_replace()

Posted on 2003-02-19
Medium Priority
Last Modified: 2006-11-17
I see that ^ and $ are included in most expressions.  Should you include them if the search string may not be at the beginning or end of the line and you are not sure how many characters will be before or after it?

For example, I want an expression that will use preg_replace() to cycle through html docs and change all the body tags (including attributes) to a comment (<!-- body variable begins here -->).

My concern is that there will be important code before or after the body tag that I want unchanged.  It is impossible to plan on the number of characters of this code, so should I use ^ and $?  Or should I just start and end the expression with /?

My code thus far is:
$text = preg_replace("/^(<body+)(.*)>+$/", "<!-- body variable begins here -->", $text)

It just deletes the body tag.  The comment is not inserted.  What am I doing wrong?

I added ^ and $, but the result was the same.
Question by:justravis
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
  • +1

Expert Comment

ID: 7983172
Try this:

Add "is", remove +

$text = preg_replace("/^(<body)(.*)>+$/is", "<!-- body variable begins here -->", $text)

Expert Comment

ID: 7988212
Why a regular expression?

You can do:

$html = str_replace('<body', "<!-- body variable begins here -->\n<body", $html);

And get it all done.

This however will not work if you've got a whole load of other possibilities OR if tag body can also be in mixed case. There is stri_replace() function in CVS now, but will be only available some time later.

str_replace() is also significally faster than preg_replace.

As of preg, you could do this:

$html = preg_replace("/<body/i", "<\!-- body variable begins here -->\n<body", $html);

Hope this helps
Maxim Maletsky

Author Comment

ID: 7989921
Hi Maxim.  I think I hav seen your comments in the manual.

For some reason, I thought str_replace did not support regex.  Only simple replacements.

I want the code to replace the whole body tag including attributes that me be there, so I need regex.

I'll try yr sugestions and answer back today.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 7995953
Here is what happened when I tried to implement your ideas:
        #Big Red Dog @ Experts-Exchange.com
        #Result: Outputs comment, but replaces body tag as well as all text that follows.
        #$text = preg_replace("/^(<body)(.*)>+$/is", "<!-- body variable begins here -->", $text);

        #S-Maxim (maxim@php.net) @ Experts-Exchange.com
        #Result: Simply outputs comment before body tag.
        #$text = preg_replace("/<body/i", "<\!-- body variable begins here -->\n<body", $text);

Got this working pretty well:
[php]$text = preg_replace("/<(B|b)(O|o)(D|d)(Y|y)(.*)>{1}/", "<!-- body variable begins here --
>", $text);[/php]

Only problem is that it also replaces any other tags immediately following.  I'm thinking it is looking for the last '>' on that line.  Shouldn't '>{1}/' make it stop after first occurrence?  Any ideas?

Author Comment

ID: 7998204
Found solution, but don't understand why.

[php]$text = preg_replace("/<(B|b)(O|o)(D|d)(Y|y)(.*?)>/", "<!-- body variable begins here -->"
, $text);[/php]

Adding the question mark limited the replace to only the body tag.  It no longer replaces any tags or comments on the same line.  Does anybody know the siginifance of using '*' and '?' together?  To me, the '?' would just override the '*'.

I cut out the {1} after the '>' because it didn't seem to make a difference either way.

Accepted Solution

Big_Red_Dog earned 200 total points
ID: 8000526
Yes, "if a quantifier is followed  by  a  question  mark,
then it ceases to be greedy, and instead matches the minimum number of times possible".

This comes from http://www.php.net/manual/en/pcre.pattern.syntax.php about 1/2 way down the page.

Expert Comment

ID: 8221770
So is everything working for you now?

Author Comment

ID: 8228532
Sorry.  For the delay.  Is it possible to divy up the pioints?  If so, how?

Expert Comment

ID: 8228662
There are two ways:

1) Go to http://www.experts-exchange.com/Community_Support/ and ask them to split the points for http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_20521028.html however you want.

2) Award these points to one person, and then in your closing comment indicate that you have created another question with the subect of "Points for xxx" where xxx is whoever else you want to give points to, then only accept a reply from that person.

Expert Comment

ID: 8230691
Dear justravis

I've refunded 25 points to enable you to accept the comment of Big_Red_Dog and to post a "Points for <expertname>" Q for the other expert in the same topic area.

1) Post the link to the original Q in the "Points for <expertname>" and
2) Add in the original Q a comment with the link to the "Points for <expertname>", thus the email notif will warn the expert.


Community Support Moderator
Experts Exchange

Expert Comment

ID: 8246834

s-maxim points at:


Community Support Moderator
Experts Exchange

Featured Post

Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

771 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