John Davidson

RegEx to remove all properties from style attribute except font-family in php

0 comments
Message:


I want to remove all properties from style attribute except font-family in php


I have tried this


style=(.*)font-[^;]+;

Example html


<div style='margin: 0px 14.3906px 0px 28.7969px; padding: 0px; width: 436.797px; float: left; font-family: "Open Sans", Arial, sans-serif;'><p style="margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding: 0px; text-align: justify;"><strong style="margin: 0px; padding: 0px;">Lorem Ipsum</strong>&nbsp;is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><div><br></div></div><div style='margin: 0px 28.7969px 0px 14.3906px; padding: 0px; width: 436.797px; float: right; font-family: "Open Sans", Arial, sans-serif;'></div>

expected output


<div style='font-family: "Open Sans", Arial, sans-serif;'><p><strong>Lorem Ipsum</strong>&nbsp;is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><div><br></div></div><div style='font-family: "Open Sans", Arial, sans-serif;'></div>

but not working as expected. Anything need to change in this?



My Answer:
You can achieve this using the following regular expression in PHP:

php
$html = '
Hello World
';

$pattern = '/style="([^"]*?)"/';
$replacement = 'style="$1"';
$html = preg_replace_callback($pattern, function($matches) {
$styles = explode(';', $matches[1]);
$filteredStyles = array_filter($styles, function($style) {
return strpos($style, 'font-family') !== false || strpos($style, 'font-family') === 0;
});
return 'style="' . implode(';', $filteredStyles) . '"';
}, $html);

echo $html;


This code will remove all properties from the `style` attribute except `font-family` in the given HTML.

Rate this post

5 of 5 based on 4189 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us