0

How do I remove all form elements and their contents using php. What pattern should I insert in preg_replace;

HTML string:

<p>Hey I am a boy</p>
<form id='id1' class='class1'>Content</form>
<p>Hey I am a girl</p>
<form id='id1' class='class1'>content</form>

Preg_replace should return string:

<p>I am a boy</p>
<p>Hey I am a girl</p>

i want all form elements stripped out of return string

user1502826
  • 395
  • 4
  • 12

4 Answers4

3

Use the below regex and then replace the match with an empty string.

(?s)(^|\n)?<form\b.*?<\/form>

DEMO

Explanation:

(?s)                     set flags for this block (with . matching
                         \n) (case-sensitive) (with ^ and $
                         matching normally) (matching whitespace
                         and # normally)
(                        group and capture to \1 (optional):
  ^                        the beginning of the string
 |                        OR
  \n                       '\n' (newline)
)?                       end of \1 (NOTE: because you are using a
                         quantifier on this capture, only the LAST
                         repetition of the captured pattern will be
                         stored in \1)
<form                    '<form'
\b                       the boundary between a word char (\w) and
                         something that is not a word char
.*?                      any character (0 or more times)
<                        '<'
\/                       '/'
form>                    'form>'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1
<form[^>]*>((?!<\/form>).)*<\/form>

Try this.Replace by empty string.See demo.

http://regex101.com/r/dZ1vT6/17

vks
  • 67,027
  • 10
  • 91
  • 124
0

You can use this :

preg_replace('#<form*>*</form>#isU','',$str);
Caduchon
  • 4,574
  • 4
  • 26
  • 67
0

You can use strip_tag to remove all tags but pass the <p> as a second parameter to return only that.

echo strip_tags($text, '<p>');

If that doesn't work, use:

echo preg_replace('/<form[^>]*>([\s\S]*?)<\/form[^>]*>/', '', '$text);
Shems Eddine
  • 141
  • 11
  • It doesn't remove contents of tags other than `

    `. `strip_tags` only strips tags and don't remove content.

    – nhahtdh Oct 15 '14 at 10:36