Jump to content

Regular Expressions and preg_replace


grazzman

Recommended Posts

Need some help.... All the code below is working fine but the first 2 lines. I am trying to remove everthing between the FORM tags but its not working....

[code]
$patterns[0] = '/<form.+form>/';
$replacements[0] = ' ';
$patterns[1] = '/<tr.+?>/';
$replacements[1] = '<br>';
$patterns[2] = '/<td.+?>/';
$replacements[2] = ' ';
$patterns[3] = '/:/';
$replacements[3] = '=';

$test1 = preg_replace($patterns, $replacements, $result);

[/code]

results is a html page that I'm getting using a CURL. I need the preg_replace to go from form to form then its being replaced with " ".  The other 2 replace lines work great.

Thanks guys...
Link to comment
Share on other sites

The dot metacharacter matches "everything [i]but[/i] a new line." As a result, your pattern will only work when the form tags are on the same line. To make the dot [i]really[/i] match everything, use the 's' modifier: [tt]/<form.+form>/s[/tt]
Link to comment
Share on other sites

well, that worked, a little to well. Their is more then one form on the page, one near the top and one near the bottom. With the /s its removing everything from the first <form> tag to the last </form> tag on the page where I need it to remove each <form> and leave everthing else... if that makes sense..... I hope...

<form> NEED this removed </form>

NEED this to stay, with the /s this is removed...

<form> NEED this removed</form>
Link to comment
Share on other sites

All quantifiers are greedy by default. This means they match as much as possible, thus your first and last form tag. In order to match as little as possible, quantifiers must be ungreedy. This is done in two ways:

1. Place a question mark after a quantifier in order to affect only that quantifier: [tt]/<form.+?form>/s[/tt]
2. Use the 'U' switch to make all quantifiers ungreedy by default: [tt]/<form.+form>/Us[/tt]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.