RE: [PHP] eregi_replace and regular expressions
| From: | John W. Holmes | Date: | Mon, 30 Sep 2002 16:48:02 +0000 |
| Subject: | RE: [PHP] eregi_replace and regular expressions | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-118232@lists.php.net to get a copy of this message | ||
> I am trying to add html code using php on the fly while uploading web
> pages
> to our database. All of my replace functions seem to work well except
> one.
> I am trying to add a <table> tag after the body tag. It is easy to
find
> the body tag because there is only one "<body" in an html document. I
am
> having a terrible time trying to find the end of the tag because it
has
> unknown length and contents, but it does end with a ">". So here is
what
> I've tried:
>
> $filedata = eregi_replace("<body(.*)>","<body\\1><table border=0
> width='80%'>",$filedata);
>
> This line of code happily adds the <table border=0 width='80%'> at the
end
> of the document. eregi_replace uses a case insensitive matching. The
reg
> exp is matching the entire $filedata rather than stopping at the first
">"
> after "<body". How do I get it to stop at the first ">" after
> "<body"?
It's being greedy. You are telling it to match anything and everything,
and then end with a >.
Try something like this, instead.
eregi_replace("<body([^<]*)>"
That'll match anything after body and between the closing > tag, but
won't match the < of the next tag. Don't know if I explained that very
well, but have a go at it. :)
---John Holmes...