Hello kind people, do not judge strictly for a child's question, I just learn. PHP has a strip_tags function that removes html tags in a string. In the second parameter, you can specify exceptions, i.e. Those tags that it should leave, for example like this:

echo strip_tags($text, '<i><u><b>'); 

Question; is it possible, on the contrary, to indicate in the function those parameters that it should delete, and leave everything else? for example

 функция($text,<a>) //удалить теги <a> а все остальные оставить 

Not necessarily just strip_tags (), you can offer an analogue. I can make up a regular expression, but can there be a special function?

  • one
    There is no such function, just write an analog or use regular expressions. - And

2 answers 2

You can also do without the use of third-party libraries. This function will delete the tags passed to its input by the second parameter. You can send more than one tag, separating them with a comma (with or without a space) .

Examples of using:

 // Удалить только теги "a" (текст тега останется) echo del_tags($text, 'a'); // Удалить теги "a" и "br" echo del_tags($text, 'a,br'); // Или с пробелами между именами тегов echo del_tags($text, 'a, br'); // и т.д. function del_tags($txt, $tag) { $tags = explode(',', $tag); do { $tag = array_shift($tags); $txt = preg_replace("~<($tag)[^>]*>|(?:</(?1)>)|<$tag\s?/?>~x", '', $txt); } while (!empty($tags)); return $txt; } 

Demo

  • one
    @Igor Salamov The current implementation removes only tags. If you do not need to leave text between tags (for example) <a>текст</a> , then I will correct the template. - Edward

You can use the HTML Purifier library.

It does not work very quickly, but it does its job, a config example for your case:

 $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.AllowedElements', ['a']); // Разрешаем только тег a $config->set('HTML.AllowedAttributes', ['a.href']); // Разрешает использовать только атрибут href у тега a $purifier = new HTMLPurifier($config); $clear_text = $purifier->purify($text); 

He has a lot of opportunities, you can read at your leisure, maybe there is somewhere and a Russian description.