Page 1 of 1

Matching content within tag

Posted: Thu Feb 04, 2010 4:16 pm
by tristanlee85
This has got to be the most straight-forward question ever asked, but I can not get this to match at all.

I have the following:

Code: Select all

<form id="myForm" action="" method="get">
<table>
<tr><td>field1</td><td><input type="text" id="field1" value="" /></td></tr>
<tr><td>field2</td><td><input type="text" id="field2" value="" /></td></tr>
</table>
</form>
And I am trying to match everything within the <form...></form> tags. The regex I am using is:

Code: Select all

<form[^>](.*)</form>
This is stumping me. Is it because there are additional <'s and >'s in the content I'm trying to match?

Re: Matching content within tag

Posted: Fri Feb 05, 2010 1:13 pm
by prometheuzz
Try:

Code: Select all

$regex = '#<form[^>]*>(?:(?!</form>).)*+</form>#is';
Although using a (x)html parser would be a better approach.

Re: Matching content within tag

Posted: Sun Feb 07, 2010 11:05 am
by ridgerunner
prometheuzz wrote:Try:

Code: Select all

$regex = '#<form[^>]*>(?:(?!</form>).)*</form>#is';
Although using a (x)html parser would be a better approach.
or simpler still....

Code: Select all

$regex = '#<form[^>]*>(.*?)</form>#is';

Re: Matching content within tag

Posted: Wed Feb 10, 2010 6:18 am
by klevis miho
Try this:

'#<form>(.+?)</form>#s'

preg_match('#<form>(.+?)</form>#s', $content, $matches);
echo $matches[0];

I use it all the time

Re: Matching content within tag

Posted: Thu Feb 11, 2010 12:34 pm
by ridgerunner
klevis miho wrote:Try this:

'#<form>(.+?)</form>#s'

preg_match('#<form>(.+?)</form>#s', $content, $matches);
echo $matches[0];

I use it all the time
Your regex does not allow attributes in the form element!

Re: Matching content within tag

Posted: Thu Feb 11, 2010 1:45 pm
by klevis miho
Yeah you right :)

'#<form(.+?)</form>#s'