2015-09-04 54 views

回答

2

You can remove all strings that look like <...> other than <a> or </a> with

<(?!\/?a>)[^>]*> 

See demo

不要忘記添加/i不區分大小寫的修改也避免匹配<A>。如果您不打算繼續關閉</a>,則可以使用<(?!a>)[^>]*>

+0

我加了可選的'\ /?' - 我想你也想保留結束標記,對吧?我還用我以前的正則表達式添加了該筆記。 –

1

試試這個:

function strip_tags(input, allowed) { 
    allowed = (((allowed || '') + '') 
    .toLowerCase() 
    .match(/<[a-z][a-z0-9]*>/g) || []) 
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>) 
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, 
    commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi; 
    return input.replace(commentsAndPhpTags, '') 
    .replace(tags, function($0, $1) { 
     return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; 
    }); 
} 

var html = 'some html code'; 
html = strip_tags(html, '<a>'); 

來源:http://phpjs.org/functions/strip_tags/

相關問題