אם היית מסתכל בתגובות לפונקציה strip_tags היית מוצא לא מעט פתרונות כאלו:
PHP קוד:
<?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
?>
PHP קוד:
function strip_selected_tags($str, $tags = "", $stripContent = false)
{
preg_match_all("/<([^>]+)>/i", $tags, $allTags, PREG_PATTERN_ORDER);
foreach ($allTags[1] as $tag) {
$replace = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
$replace2 = "%(<$tag.*?>)%is";
echo $replace;
if ($stripContent) {
$str = preg_replace($replace,'',$str);
$str = preg_replace($replace2,'',$str);
}
$str = preg_replace($replace,'${2}',$str);
$str = preg_replace($replace2,'${2}',$str);
}
return $str;
}
ויש שם עוד כמה, פעם הבאה תעבור על התגובות שם, יש שם אחלה פונקציות שעוזרות המון