Maybe it’s easier to use one parser HTML, such as the Domdocument, for example:
$dom = new DOMDocument;
$dom->loadHtml($html); // $html é uma string contendo o HTML
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//i[contains(@class, 'fa-')]") as $i) { // procura elementos i com classe fa-*
$i->parentNode->removeChild($i);
}
echo $dom->saveHTML();
In case, I look for elements i
containing a class whose name begins with fa-
, and remove them from HTML.
With regex is a little more complicated, but we can assume that the tag i
is always in this format (<i class="classes"></i>
): no content between opening and closing the tag, and always with the names of the classes in the attribute class
(and no other attribute). So regex could be something like:
$str = 'Texto de teste <i class="fab fa-accusoft"></i> Teste Lorem Ipsim <i class="fab fa-accusoft"></i> abc etc';
echo preg_replace('/<i class="[^"]*\bfa-[^"]*"><\/i>/', '', $str);
I use a character class denied ([^"]
), which means anything that nay be it "
. So I check if inside the quotes there is a class whose name is fa-(qualquer-coisa)
.
I use the shortcut \b
(word Boundary) to ensure that before the f
no alphanumeric character exists, thus avoiding false-positives (such as a name alfa-alguma-coisa
).
The result is that tags i
are removed:
Texto de teste Teste Lorem Ipsim abc etc
But note that spaces before and after the tag are not removed (although this will make no difference in HTML). But if you really want to remove them, you can switch to:
preg_replace('/ *<i class="[^"]*\bfa-[^"]*"><\/i>/', '', $str);
Notice that now, before the <i
there is a space followed by the quantifier *
, meaning "zero or more occurrences". Thus, the spaces before the tag i
are also removed.
If you only have these simple cases, this regex should be enough. If you have more complicated cases, then it will probably be better to use DOMDocument
even. Regex is not the best tool to work with HTML.
You want to remove from the document still on the server-side, or just not visible on the screen?
– hugocsl