This question already has an answer here:
I've been looking for answer but i didn't find.
I want to remove classes b-c
and e
from string which contains html.
$tmp = '<div class="a b-c d e">b-c</div>';
$tmp2 = '<div class="a b-c d">b-c</div>';
$tmp3 = '<div class="a e b-c d">b-c</div>';
$tmp4 = '<div class="a d e">b-c</div>';
I tried somethinkg like this
preg_replace('#class="(.*?)(b-c|e)(.*?)"#si', 'class="\\1\\3"', $a)
but it doesn't work in all cases(not for $tmp
and $tmp2
).
After regex $tmp
,$tmp2
, $tmp3
, $tmp4
should
<div class="a d">b-c</div>
I would like this regex will remove all classes in all cases regardless of how many classes there are and regardless of order Can anyony help me? I'm not good in regex :/
</div>
You can try the following code using str_replace
str_replace(" b-c ", " ", $tmp); // This will replace b-c if it is not the first or last class
str_replace("b-c ", " ", $tmp); // This will replace b-c if it is the first class
str_replace(" b-c", " ", $tmp); // This will replace b-c if it is the last class
str_replace('"b-c"', '""', $tmp); // This will replace b-c if it is the only class and the quotes for the class HTML property are double quotes
This code won't delete the b-c
that is in <div>b-c</div>
because it searches for b-c
with spaces before or after
If you want to use regex (but is always better to use a DOM parser), you can reach your goal in this way:
<?php
$tmp = '<div class="a b-c d e">b-c</div>';
$tmp2 = '<div class="a b-c d">b-c</div>';
$tmp3 = '<div class="a e b-c d">b-c</div>';
$tmp4 = '<div class="a d e">b-c</div>';
function remove($tmp) {
return preg_replace_callback('/class="([^"]+)"/', function($m) {
if(strpos($m[1], "b-c") !== false) {
$m[0] = preg_replace("/\s*b-c\s*/",' ',$m[0],1);
}
if(strpos($m[1],"e") !== false) {
$m[0] = preg_replace("/\s*e\s*/",' ',$m[0], 1);
}
return $m[0];
}, $tmp);
}
echo remove($tmp), "
", remove($tmp2), "
", remove($tmp3), "
" , remove($tmp4);
Outputs:
<div class="a d ">b-c</div>
<div class="a d">b-c</div>
<div class="a d">b-c</div>
<div class="a d ">b-c</div>
Not perfect (there's a trailing space) but it works well (spaces are allowed in class attribute).
I hope it helps