PHP Batch substitution HTML tag instance code _php tips

Source: Internet
Author: User

1. Remove all HTML elements, or keep a few HTML tags

Copy Code code as follows:

<?php
$text = ' <p>test paragraph.</p><!--Comment--> <a href= ' #fragment ' >other text</a> ';
echo Strip_tags ($text);
echo "/n";

Allow <p> and <a>
Echo strip_tags ($text, ' <p><a> ');
?>


The result is (minus the note):

<blockquote>test paragraph. Other text
<p>test paragraph.</p> <a href= "#fragment" >other text</a></blockquote>2. Instead, Remove only one HTML tag

Copy Code code as follows:

<?php
function Strip_only ($str, $tags, $stripContent = False) {
$content = ';
if (!is_array ($tags)) {
$tags = (Strpos ($str, ' > ')!== false Explode (' > ', Str_replace (' < ', ', $tags)): Array ($tags));
if (end ($tags) = = ") Array_pop ($tags);
}
foreach ($tags as $tag) {
if ($stripContent)
$content = ' (. +</'. $tag. [^>]*>|) ';
$str = Preg_replace (' #</? '). $tag. ' [^>]*> '. $content. ' #is ', ', $str);
}
return $str;
}

$str = ' <font color= ' red ' >red</font> text ';
$tags = ' font ';
$a = strip_only ($str, $tags); Red text
$b = Strip_only ($str, $tags, true); Text
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.