开发者

preg_replace() - removing a string contained within html tags

I want to do the following:

I have a string in a database, it is stored with html tags when being inserted there, so for example, I might have the following string:

     <h2>Hello World</h2>
     <p>Cras mattis justo vitae diam sagittis ut porta eros aliquam. 
        Aenean vel nisi et nisl adipiscing blandit. 
        Donec tempor dictum risus a feugiat. 
        Nunc ac purus lectus. Morbi in suscipit ipsum. 
        Ut eu odio eu massa sollicitudin interdum. 
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
        Maecenas fermentum hendrerit imperdiet.</p>

This is a string I might have in the database, and I want to discard the <h2> part of it.

Now, as far as I know, doing a preg_replace() here, would do the job, but what string 开发者_如何学Gopattern do I need to look for?

Many thanks.


See the Remove HTML Tags section on the linked site. E.g.

@<h2[^>]*?>.*?</h2>@siu


To actually answer your question the replace method RegEx would be:

/<h2>(.+?)<\/h2>/

However, as the comments pointed out, this isn't the best method! :)


Nice by Michael Wright.

Another way to solve this problem using strip_tags() function.

  $patern = '<p>';
  $str = '<h2>Hello World</h2><p>Cras mattis justo vitae diam .</p>';
  strip_tags($str,$patern);

This code generate the following output

 'Hello World<p>Cras mattis justo vitae diam .</p>'

Here $pattrn contain the tag list that still remain in you data. strip_tags() eliminates all tags except in $patern.

reference from php manual

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜