Skip to content

Instantly share code, notes, and snippets.

@greg-randall
Last active March 1, 2019 18:03
Show Gist options
  • Save greg-randall/1fd0176cba852a0d4942cdcbeb1a825c to your computer and use it in GitHub Desktop.
Save greg-randall/1fd0176cba852a0d4942cdcbeb1a825c to your computer and use it in GitHub Desktop.
Remove all html attributes except for the url of images and urls on links. It then cleans up html removing divs, spans, etc. Ideally used if you have a source of HTML from an existing site with a bunch of CSS classes you don't need.
<?php
if(!isset($_POST["input"])|$_POST["input"]==""){ //check to see if the url is set. if not set prompts for a url.
?>Clean:
<form action="index.php" method="post">
<textarea name="input" rows="40" cols="80"></textarea><br><br>
<input type="submit">
</form><?php
exit();
}else{
$input = htmlspecialchars_decode($_POST["input"]);
//get all html elements on a line by themselves
$input = str_replace (array("<",">"),array("\n<",">\n"),$input);
//find lines starting with a '<' and any letters or numbers upto the first space. throw everything after the space away.
$clean = str_replace('"',"'",$input);
$clean = strip_tags($clean, '<h1><h2><h3><h4><h5><h6><img><a><abbr><acronym><applet><area><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><dl><dt><em><embed><fieldset><figcaption><figure><font><form><frame><frameset><h1><head><hr><html><i><iframe><input><ins><kbd><label><legend><li><link><main><map><mark><menu><menuitem><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><select><small><source><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video><wbr>');
$clean = preg_replace("/\n(<[^ai]([\w\d]+)?).+/i","\n$1>",$clean);
$clean = preg_replace("/<a.+href='([:\w\d#\/\-\.]+)'.+/i","<a href=\"$1\">",$clean);
$clean = preg_replace("/<img.+src='([\w\d_:?.\/%=\-]+)'.+/i","<img src=\"$1\">",$clean);
$clean = str_replace("'",'"',$clean);
$clean = str_replace("&nbsp;",' ',$clean);
$clean = preg_replace("/[\s\n\r]+/i"," ",$clean);
$clean = str_replace('> <','><',$clean);
$clean = preg_replace("/<([\w\d]+)><\/\\1>/i","",$clean);
$url = 'https://www.10bestdesign.com/dirtymarkup/api/html';
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(
array(
'code' => $clean,
'output' => 'fragment',
)
),
'timeout' => 60
)
));
$resp = file_get_contents($url, FALSE, $context);
$resp=json_decode($resp, true);
echo "<pre>".htmlspecialchars (array_pop($resp));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment