从字符串中搜索并替换html元素


Search and replace html element from string

如何使用php删除所有表单元素及其内容。我应该在preg_replace中插入什么模式;

HTML字符串:

<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应返回字符串:

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

我希望从返回字符串中剥离所有表单元素

使用下面的正则表达式,然后用空字符串替换匹配项。

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

演示

解释:

(?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>'
<form[^>]*>((?!<'/form>).)*<'/form>

试试这个。替换为empty string。请参阅演示。

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

您可以使用这个:

preg_replace('#<form*>*</form>#isU','',$str);

您可以使用strip_tag来删除所有标记,但将<p>作为第二个参数来只返回。

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

如果不起作用,请使用:

echo preg_replace('/<form[^>]*>(['s'S]*?)<'/form[^>]*>/', '', '$text);