Regular Expressions & preg_replace()
Posted on 2003-02-19
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.