I
I
i_osif2018-01-28 22:41:26
Regular Expressions
i_osif, 2018-01-28 22:41:26

How to remove all attributes from a tag except some?

Hello!
There is a line:

<img title="тест" id="hh" alt="fff" src="/test/" align="left" width="500" dddd="dd" height="300">

It is necessary to remove all attributes from it except align, title, alt, height, width, src
How to write a correct regular expression?
Preferably done via preg_replace (php).
Rescue dear experts in regular expressions, do not let the abyss.
Sincerely

Answer the question

In order to leave comments, you need to log in

2 answer(s)
4
4iloveg, 2018-01-29
@4iloveg

https://regex101.com/r/JO2yxA/1

M
mrWan, 2018-01-29
@mrWan

$subject = '<a  attr1="val1" attr2 = "" attr3 href="/link/?pa=234kjh&ff=09" attr4="val4" title="title">привет anchor 245</a>';
$pattern = '/((?:href|title)=\"[^"]+\").+?((?:href|title)=\"[^"]+")[^>]{0,}>([^<]+)/i';
preg_match($pattern,$subject,$match);
array_shift($match);
$text = array_pop($match);
$attrs = join(' ',$match);
$a_new = '<a '.$attrs.'>'.$text.'</a>';
echo htmlspecialchars($a_new);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question