Matching content within tag

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
tristanlee85
Forum Contributor
Posts: 172
Joined: Fri Dec 19, 2003 7:28 am

Matching content within tag

Post 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?
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Matching content within tag

Post by prometheuzz »

Try:

Code: Select all

$regex = '#<form[^>]*>(?:(?!</form>).)*+</form>#is';
Although using a (x)html parser would be a better approach.
Last edited by prometheuzz on Sun Feb 07, 2010 12:27 pm, edited 1 time in total.
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Matching content within tag

Post 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';
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Matching content within tag

Post by klevis miho »

Try this:

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

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

I use it all the time
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Matching content within tag

Post 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!
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Matching content within tag

Post by klevis miho »

Yeah you right :)

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