Messages popping up on wordpress load - php

I am trying to hide the following message that keeps on showing when I load any wordpress page:
Force Word Wrapping. For support / comments / whatever, visit the support forums. Version: 1.0.0 Author: Jim Wigginton Author URI: http://www.frostjedi.com/ */ function word_wrap_pass($message) { $wrapAt = 70; $tempText = ''; $finalText = ''; $curCount = $tempCount = 0; $longestAmp = 9; $inTag = false; $ampText = ''; $len = strlen($message); for ($num=0;$num<$len;$num++) { $curChar = $message{$num}; if ($curChar == '<') { for ($snum=0;$snum') { $tempText .= '>'; $inTag = false; } elseif ($inTag) { $tempText .= $curChar; } elseif ($curChar == '&') { for ($snum=0;$snum= $longestAmp || $curChar == ';') { for ($snum=0;$snum= $maxChars) { $finalText .= $tempText . ' '; $tempText = ''; $curCount = 1; } else { $tempText .= $curChar; $curCount++; } // the following code takes care of (unicode) characters prohibiting non-mandatory breaks directly before them. // $curChar isn't a " " or "\n" if ($tempText != '' && $curChar != '') { $tempCount++; } // $curChar is " " or "\n", but $nextChar prohibits wrapping. elseif ( ($curCount == 1 && strstr($wrapProhibitedChars,$curChar) !== false) || ($curCount == 0 && $nextChar != '' && $nextChar != ' ' && $nextChar != "\n" && strstr($wrapProhibitedChars,$nextChar) !== false)) { $tempCount++; } // $curChar and $nextChar aren't both either " " or "\n" elseif (!($curCount == 0 && ($nextChar == ' ' || $nextChar == "\n"))) { $tempCount = 0; } if ($tempCount >= $maxChars && $tempText == '') { $finalText .= ' '; $tempCount = 1; $curCount = 2; } if ($tempText == '' && $curCount > 0) { $finalText .= $curChar; } } add_filter('the_content', 'word_wrap_pass'); add_filter('comment_text', 'word_wrap_pass'); ?>
I've tried many different things including what is in this How can I stop PHP notices from appearing in wordpress?.
Any help would be appreciated

Hard to tell with just the code you are showing... we'd need more information to properly answer this. But, this message appears to be coming from one of your plugins that has been improperly coded. I would disable all plugins, then enable one at a time until this message shows again. That will be your faulty plugin. Permanently disable it/delete it... or contact the author to ask them to fix it if you really need it.

Related

Auto Description From Tags

I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.

PHP4 (legacy servers) XML=>JSON converion, a la simplexml_file_load() or simpleXMLelement

I'm developing on a server using an old version of PHP (4.3.9), and I'm trying to convert an XML string into a JSON string. This is easy in PHP5, but a lot tougher with PHP4.
I've tried:
Zend JSON.php
require_once 'Zend/Json.php';
echo Zend_Json::encode($sxml);
Error:
PHP Parse error: parse error, unexpected T_CONST, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}'
simplexml44
$impl = new IsterXmlSimpleXMLImpl;
$NDFDxmltemp = $impl->load_file($NDFDstring);
$NDFDxml = $NDFDxmltemp->asXML();
Error:
WARNING isterxmlexpatnonvalid->parse(): nothing to read
xml_parse
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "_start_element", "_end_element");
xml_set_character_data_handler($xml_parser, "_character_data");
xml_parse($xml_parser, $NDFDstring);
Error:
PHP Warning: xml_parse(): Unable to call handler _character_data() in ...
PHP Warning: xml_parse(): Unable to call handler _end_element() in ...
Does anyone have any other alternatives to simplexml_file_load() and new simpleXMLelement in PHP4?
Upgrading PHP is not an option in this particular case, so do not bother bringing it up. Yes, I know its old.
NOTE: This is the XML I'm trying to parse into a multidimensional array OR json.
http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?lat=40&lon=-120&product=time-series&begin=2013-10-30T00:00:00&end=2013-11-06T00:00:00&maxt=maxt&mint=mint&rh=rh&wx=wx&wspd=wspd&wdir=wdir&icons=icons&wgust=wgust&pop12=pop12&maxrh=maxrh&minrh=minrh&qpf=qpf&snow=snow&temp=temp&wwa=wwa
XML are quite easy to parse by yourself, anyway here is exists xml_parse in php 4 and domxml_open_file
and here is json for php4 and another one
according parsing xml:
if you know the structure of xml file, you can go even with RegExp, as XML is strict format (I mean all tags must be closed, all attributes in quotes, all special symbols always escaped)
if you parse arbitrary xml file, here is student sample, which works with php4, do not understand all XML features, but can give you "brute-force" like idea:
<?php
define("LWG_XML_ELEMENT_NULL", "0");
define("LWG_XML_ELEMENT_NODE", "1");
function EntitiesToString($str)
{
$s = $str;
$s = eregi_replace(""", "\"", $s);
$s = eregi_replace("<", "<", $s);
$s = eregi_replace(">", ">", $s);
$s = eregi_replace("&", "&", $s);
return $s;
}
class CLWG_dom_attribute
{
var $name;
var $value;
function CLWG_dom_attribute()
{
$name = "";
$value = "";
}
}
class CLWG_dom_node
{
var $m_Attributes;
var $m_Childs;
var $m_nAttributesCount;
var $m_nChildsCount;
var $type;
var $tagname;
var $content;
function CLWG_dom_node()
{
$this->m_Attributes = array();
$this->m_Childs = array();
$this->m_nAttributesCount = 0;
$this->m_nChildsCount = 0;
$this->type = LWG_XML_ELEMENT_NULL;
$this->tagname = "";
$this->content = "";
}
function get_attribute($attr_name)
{
//echo "<message>Get Attribute: ".$attr_name." ";
for ($i=0; $i<sizeof($this->m_Attributes); $i++)
if ($this->m_Attributes[$i]->name == $attr_name)
{
//echo $this->m_Attributes[$i]->value . "</message>\n";
return $this->m_Attributes[$i]->value;
}
//echo "[empty]</message>\n";
return "";
}
function get_content()
{
//echo "<message>Get Content: ".$this->content . "</message>\n";
return $this->content;
}
function attributes()
{
return $this->m_Attributes;
}
function child_nodes()
{
return $this->m_Childs;
}
function loadXML($str, &$i)
{
//echo "<debug>DEBUG: LoadXML (".$i.": ".$str[$i].")</debug>\n";
$str_len = strlen($str);
//echo "<debug>DEBUG: start searching for tag (".$i.": ".$str[$i].")</debug>\n";
while ( ($i<$str_len) && ($str[$i] != "<") )
$i++;
if ($i == $str_len) return FALSE;
$i++;
while ( ($i<strlen($str)) && ($str[$i] != " ") && ($str[$i] != "/") && ($str[$i] != ">") )
$this->tagname .= $str[$i++];
//echo "<debug>DEBUG: Tag: " . $this->tagname . "</debug>\n";
if ($i == $str_len) return FALSE;
switch ($str[$i])
{
case " ": // attributes comming
{
//echo "<debug>DEBUG: Tag: start searching attributes</debug>\n";
$i++;
$cnt = sizeof($this->m_Attributes);
while ( ($i<strlen($str)) && ($str[$i] != "/") && ($str[$i] != ">") )
{
$this->m_Attributes[$cnt] = new CLWG_dom_attribute;
while ( ($i<strlen($str)) && ($str[$i] != "=") )
$this->m_Attributes[$cnt]->name .= $str[$i++];
if ($i == $str_len) return FALSE;
$i++;
while ( ($i<strlen($str)) && ($str[$i] != "\"") )
$i++;
if ($i == $str_len) return FALSE;
$i++;
while ( ($i<strlen($str)) && ($str[$i] != "\"") )
$this->m_Attributes[$cnt]->value .= $str[$i++];
$this->m_Attributes[$cnt]->value = EntitiesToString($this->m_Attributes[$cnt]->value);
//echo "<debug>DEBUG: Tag: Attribute: '".$this->m_Attributes[$cnt]->name."' = '".$this->m_Attributes[$cnt]->value."'</debug>\n";
if ($i == $str_len) return FALSE;
$i++;
if ($i == $str_len) return FALSE;
while ( ($i<strlen($str)) && ($str[$i] == " ") )
$i++;
$cnt++;
}
if ($i == $str_len) return FALSE;
switch ($str[$i])
{
case "/":
{
//echo "<debug>DEBUG: self closing tag with attributes (".$this->tagname.")</debug>\n";
$i++;
if ($i == $str_len) return FALSE;
if ($str[$i] != ">") return FALSE;
$i++;
return TRUE;
break;
}
case ">";
{
//echo "<debug>DEBUG: end of attributes (".$this->tagname.")</debug>\n";
$i++;
break;
}
}
break;
}
case "/": // self closing tag
{
//echo "<debug>DEBUG: self closing tag (".$this->tagname.")</debug>\n";
$i++;
if ($i == $str_len) return FALSE;
if ($str[$i] != ">") return FALSE;
$i++;
return TRUE;
break;
}
case ">": // end of begin of node
{
//echo "<debug>DEBUG: end of begin of node</debug>\n";
$i++;
break;
}
}
if ($i == $str_len) return FALSE;
$b = 1;
while ( ($i<$str_len) && ($b) )
{
//echo "<debug>DEBUG: searching for content</debug>\n";
while ( ($i<strlen($str)) && ($str[$i] != "<") )
$this->content .= $str[$i++];
//echo "<debug>DEBUG: content: ".$this->content."</debug>\n";
if ($i == $str_len) return FALSE;
$i++;
if ($i == $str_len) return FALSE;
if ($str[$i] != "/") // new child
{
$cnt = sizeof($this->m_Childs);
//echo "<debug>DEBUG: Create new child (" . $cnt . ")</debug>\n";
$this->m_Childs[$cnt] = new CLWG_dom_node;
$this->m_Childs[$cnt]->type = LWG_XML_ELEMENT_NODE;
$i--;
if ($this->m_Childs[$cnt]->loadXML($str, $i) === FALSE)
return FALSE;
}
else
$b = 0;
}
$i++;
$close_tag = "";
while ( ($i<strlen($str)) && ($str[$i] != ">") )
$close_tag .= $str[$i++];
//echo "<debug>DEBUG: close tag: ".$close_tag." - ".$this->tagname."</debug>\n";
if ($i == $str_len) return FALSE;
$i++;
$this->content = EntitiesToString($this->content);
//echo "<debug>DEBUG: content: ".$this->content."</debug>\n";
return ($close_tag == $this->tagname);
}
}
class CLWG_dom_xml
{
var $m_Root;
function CLWG_dom_xml()
{
$this->m_Root = 0;
}
function document_element()
{
return $this->m_Root;
}
function loadXML($xml_string)
{
// check xml tag
if (eregi("<\\?xml", $xml_string))
{
// check xml version
$xml_version = array();
if ( (eregi("<\\?xml version=\"([0-9\\.]+)\".*\\?>", $xml_string, $xml_version)) && ($xml_version[1] == 1.0) )
{
// initialize root
$this->m_Root = new CLWG_dom_node;
$i = 0;
return $this->m_Root->loadXML(eregi_replace("<\\?xml.*\\?>", "", $xml_string), $i);
}
else
{
echo "<error>Cannot find version attribute in xml tag</error>";
return FALSE;
}
}
else
{
echo "<error>Cannot find xml tag</error>";
return FALSE;
}
}
}
function lwg_domxml_open_mem($xml_string)
{
global $lwg_xml;
$lwg_xml = new CLWG_dom_xml;
if ($lwg_xml->loadXML($xml_string))
return $lwg_xml;
else
return 0;
}
?>
PHP4 has no support for ArrayAccess nor does it have the needed __get(), __set() and __toString() magic methods which effectively prevents you from creating an object mimicking that feature of SimpleXMLElement.
Also I'd say creating an in-memory structure yourself which is done by Simplexml is not going to work out well with PHP 4 because of it's limitation of the OOP-object-model and garbage collection. Especially as I would prefer something like the Flyweight pattern here.
Which brings me to the point that you're probably more looking for an event or pull-based XML parser.
Take a look at the XML Parser Functions which are the PHP 4 way to parse XML with PHP. You find it well explained in years old PHP training materials also with examples and what not.

php regular comment remove

how remove multi line comment ? ( /* comment php */) from file .php
how remove single comment ? ( // coment ) from file.php
how remove enter end line ?
sample :
single comment line
$G["url"] = "http://".$_SERVER["HTTP_HOST"]
multi comment line
/*
* 310
* - "::"
* - $col
*/
Try using the code posted below, it even ignores comment tokens on strings like " /* comment2 */ "
<?php
$fileIn = "src.php";
$fileOut = "srcCompressed.php";
$text = file_get_contents($fileIn);
$text = compress_php_src($text);
file_put_contents($fileOut, $text);
function compress_php_src($src) {
// Whitespaces left and right from this signs can be ignored
static $IW = array(
T_CONCAT_EQUAL, // .=
T_DOUBLE_ARROW, // =>
T_BOOLEAN_AND, // &&
T_BOOLEAN_OR, // ||
T_IS_EQUAL, // ==
T_IS_NOT_EQUAL, // != or <>
T_IS_SMALLER_OR_EQUAL, // <=
T_IS_GREATER_OR_EQUAL, // >=
T_INC, // ++
T_DEC, // --
T_PLUS_EQUAL, // +=
T_MINUS_EQUAL, // -=
T_MUL_EQUAL, // *=
T_DIV_EQUAL, // /=
T_IS_IDENTICAL, // ===
T_IS_NOT_IDENTICAL, // !==
T_DOUBLE_COLON, // ::
T_PAAMAYIM_NEKUDOTAYIM, // ::
T_OBJECT_OPERATOR, // ->
T_DOLLAR_OPEN_CURLY_BRACES, // ${
T_AND_EQUAL, // &=
T_MOD_EQUAL, // %=
T_XOR_EQUAL, // ^=
T_OR_EQUAL, // |=
T_SL, // <<
T_SR, // >>
T_SL_EQUAL, // <<=
T_SR_EQUAL, // >>=
);
if(is_file($src)) {
if(!$src = file_get_contents($src)) {
return false;
}
}
$tokens = token_get_all($src);
$new = "";
$c = sizeof($tokens);
$iw = false; // ignore whitespace
$ih = false; // in HEREDOC
$ls = ""; // last sign
$ot = null; // open tag
for($i = 0; $i < $c; $i++) {
$token = $tokens[$i];
if(is_array($token)) {
list($tn, $ts) = $token; // tokens: number, string, line
$tname = token_name($tn);
if($tn == T_INLINE_HTML) {
$new .= $ts;
$iw = false;
} else {
if($tn == T_OPEN_TAG) {
if(strpos($ts, " ") || strpos($ts, "\n") || strpos($ts, "\t") || strpos($ts, "\r")) {
$ts = rtrim($ts);
}
$ts .= " ";
$new .= $ts;
$ot = T_OPEN_TAG;
$iw = true;
} elseif($tn == T_OPEN_TAG_WITH_ECHO) {
$new .= $ts;
$ot = T_OPEN_TAG_WITH_ECHO;
$iw = true;
} elseif($tn == T_CLOSE_TAG) {
if($ot == T_OPEN_TAG_WITH_ECHO) {
$new = rtrim($new, "; ");
} else {
$ts = " ".$ts;
}
$new .= $ts;
$ot = null;
$iw = false;
} elseif(in_array($tn, $IW)) {
$new .= $ts;
$iw = true;
} elseif($tn == T_CONSTANT_ENCAPSED_STRING
|| $tn == T_ENCAPSED_AND_WHITESPACE)
{
if($ts[0] == '"') {
$ts = addcslashes($ts, "\n\t\r");
}
$new .= $ts;
$iw = true;
} elseif($tn == T_WHITESPACE) {
$nt = #$tokens[$i+1];
if(!$iw && (!is_string($nt) || $nt == '$') && !in_array($nt[0], $IW)) {
$new .= " ";
}
$iw = false;
} elseif($tn == T_START_HEREDOC) {
$new .= "<<<S\n";
$iw = false;
$ih = true; // in HEREDOC
} elseif($tn == T_END_HEREDOC) {
$new .= "S;";
$iw = true;
$ih = false; // in HEREDOC
for($j = $i+1; $j < $c; $j++) {
if(is_string($tokens[$j]) && $tokens[$j] == ";") {
$i = $j;
break;
} else if($tokens[$j][0] == T_CLOSE_TAG) {
break;
}
}
} elseif($tn == T_COMMENT || $tn == T_DOC_COMMENT) {
$iw = true;
} else {
if(!$ih) {
$ts = strtolower($ts);
}
$new .= $ts;
$iw = false;
}
}
$ls = "";
} else {
if(($token != ";" && $token != ":") || $ls != $token) {
$new .= $token;
$ls = $token;
}
$iw = true;
}
}
return $new;
}
?>
Credits to gelamu function compress_php_src().
There's no reason to remove comments from your code. The overhead from processing them is so incredibly minimal that it doesn't justify the effort.
I think you are probably looking for php_strip_whitespace().

Cutting text without destroying html tags

Is there a way to do this without writing my own function?
For example:
$text = 'Test <span><a>something</a> something else</span>.';
$text = cutText($text, 2, null, 20, true);
//result: Test <span><a>something</a></span>
I need to make this function indestructible
My problem is similar to
This thread
but I need a better solution. I would like to keep nested tags untouched.
So far my algorithm is:
function cutText($content, $max_words, $max_chars, $max_word_len, $html = false) {
$len = strlen($content);
$res = '';
$word_count = 0;
$word_started = false;
$current_word = '';
$current_word_len = 0;
if ($max_chars == null) {
$max_chars = $len;
}
$inHtml = false;
$openedTags = array();
for ($i = 0; $i<$max_chars;$i++) {
if ($content[$i] == '<' && $html) {
$inHtml = true;
}
if ($inHtml) {
$max_chars++;
}
if ($html && !$inHtml) {
if ($content[$i] != ' ' && !$word_started) {
$word_started = true;
$word_count++;
}
$current_word .= $content[$i];
$current_word_len++;
if ($current_word_len == $max_word_len) {
$current_word .= '- ';
}
if (($content[$i] == ' ') && $word_started) {
$word_started = false;
$res .= $current_word;
$current_word = '';
$current_word_len = 0;
if ($word_count == $max_words) {
return $res;
}
}
}
if ($content[$i] == '<' && $html) {
$inHtml = true;
}
}
return $res;
}
But of course it won't work. I thought about remembering opened tags and closing them if they were not closed but maybe there is a better way?
This works perfectly for me:
function trimContent ($str, $trimAtIndex) {
$beginTags = array();
$endTags = array();
for($i = 0; $i < strlen($str); $i++) {
if( $str[$i] == '<' )
$beginTags[] = $i;
else if($str[$i] == '>')
$endTags[] = $i;
}
foreach($beginTags as $k=>$index) {
// Trying to trim in between tags. Trim after the last tag
if( ( $trimAtIndex >= $index ) && ($trimAtIndex <= $endTags[$k]) ) {
$trimAtIndex = $endTags[$k];
}
}
return substr($str, 0, $trimAtIndex);
}
Try something like this
function cutText($inputText, $start, $length) {
$temp = $inputText;
$res = array();
while (strpos($temp, '>')) {
$ts = strpos($temp, '<');
$te = strpos($temp, '>');
if ($ts > 0) $res[] = substr($temp, 0, $ts);
$res[] = substr($temp, $ts, $te - $ts + 1);
$temp = substr($temp, $te + 1, strlen($temp) - $te);
}
if ($temp != '') $res[] = $temp;
$pointer = 0;
$end = $start + $length - 1;
foreach ($res as &$part) {
if (substr($part, 0, 1) != '<') {
$l = strlen($part);
$p1 = $pointer;
$p2 = $pointer + $l - 1;
$partx = "";
if ($start <= $p1 && $end >= $p2) $partx = "";
else {
if ($start > $p1 && $start <= $p2) $partx .= substr($part, 0, $start-$pointer);
if ($end >= $p1 && $end < $p2) $partx .= substr($part, $end-$pointer+1, $l-$end+$pointer);
if ($partx == "") $partx = $part;
}
$part = $partx;
$pointer += $l;
}
}
return join('', $res);
}
Parameters:
$inputText - input text
$start - position of first character
$length - how menu characters we want to remove
Example #1 - Removing first 3 characters
$text = 'Test <span><a>something</a> something else</span>.';
$text = cutText($text, 0, 3);
var_dump($text);
Output (removed "Tes")
string(47) "t <span><a>something</a> something else</span>."
Removing first 10 characters
$text = cutText($text, 0, 10);
Output (removed "Test somet")
string(40) "<span><a>hing</a> something else</span>."
Example 2 - Removing inner characters - "es" from "Test "
$text = cutText($text, 1, 2);
Output
string(48) "Tt <span><a>something</a> something else</span>."
Removing "thing something el"
$text = cutText($text, 9, 18);
Output
string(32) "Test <span><a>some</a>se</span>."
Hope this helps.
Well, maybe this is not the best solution but it's everything I can do at the moment.
Ok I solved this thing.
I divided this in 2 parts.
First cutting text without destroying html:
function cutHtml($content, $max_words, $max_chars, $max_word_len) {
$len = strlen($content);
$res = '';
$word_count = 0;
$word_started = false;
$current_word = '';
$current_word_len = 0;
if ($max_chars == null) {
$max_chars = $len;
}
$inHtml = false;
$openedTags = array();
$i = 0;
while ($i < $max_chars) {
//skip any html tags
if ($content[$i] == '<') {
$inHtml = true;
while (true) {
$res .= $content[$i];
$i++;
while($content[$i] == ' ') { $res .= $content[$i]; $i++; }
//skip any values
if ($content[$i] == "'") {
$res .= $content[$i];
$i++;
while(!($content[$i] == "'" && $content[$i-1] != "\\")) {
$res .= $content[$i];
$i++;
}
}
//skip any values
if ($content[$i] == '"') {
$res .= $content[$i];
$i++;
while(!($content[$i] == '"' && $content[$i-1] != "\\")) {
$res .= $content[$i];
$i++;
}
}
if ($content[$i] == '>') { $res .= $content[$i]; $i++; break;}
}
$inHtml = false;
}
if (!$inHtml) {
while($content[$i] == ' ') { $res .= $content[$i]; $letter_count++; $i++; } //skip spaces
$word_started = false;
$current_word = '';
$current_word_len = 0;
while (!in_array($content[$i], array(' ', '<', '.', ','))) {
if (!$word_started) {
$word_started = true;
$word_count++;
}
$current_word .= $content[$i];
$current_word_len++;
if ($current_word_len == $max_word_len) {
$current_word .= '-';
$current_word_len = 0;
}
$i++;
}
if ($letter_count > $max_chars) {
return $res;
}
if ($word_count < $max_words) {
$res .= $current_word;
$letter_count += strlen($current_word);
}
if ($word_count == $max_words) {
$res .= $current_word;
$letter_count += strlen($current_word);
return $res;
}
}
}
return $res;
}
And next thing is closing unclosed tags:
function cleanTags(&$html) {
$count = strlen($html);
$i = -1;
$openedTags = array();
while(true) {
$i++;
if ($i >= $count) break;
if ($html[$i] == '<') {
$tag = '';
$closeTag = '';
$reading = false;
//reading whole tag
while($html[$i] != '>') {
$i++;
while($html[$i] == ' ') $i++; //skip any spaces (need to be idiot proof)
if (!$reading && $html[$i] == '/') { //closing tag
$i++;
while($html[$i] == ' ') $i++; //skip any spaces
$closeTag = '';
while($html[$i] != ' ' && $html[$i] != '>') { //start reading first actuall string
$reading = true;
$html[$i] = strtolower($html[$i]); //tags to lowercase
$closeTag .= $html[$i];
$i++;
}
$c = count($openedTags);
if ($c > 0 && $openedTags[$c-1] == $closeTag) array_pop($openedTags);
}
if (!$reading) //read only tag
while($html[$i] != ' ' && $html[$i] != '>') { //start reading first actuall string
$reading = true;
$html[$i] = strtolower($html[$i]); //tags to lowercase
$tag .= $html[$i];
$i++;
}
//skip any values
if ($html[$i] == "'") {
$i++;
while(!($html[$i] == "'" && $html[$i-1] != "\\")) {
$i++;
}
}
//skip any values
if ($html[$i] == '"') {
$i++;
while(!($html[$i] == '"' && $html[$i-1] != "\\")) {
$i++;
}
}
if ($reading && $html[$i] == '/') { //self closed tag
$tag = '';
break;
}
}
if (!empty($tag)) $openedTags[] = $tag;
}
}
while (count($openedTags) > 0) {
$tag = array_pop($openedTags);
$html .= "</$tag>";
}
}
It's not idiot proof but tinymce will clear this thing out so further cleaning is not necessary.
It may be a little long but i don't think it will eat a lot of resources and it should be faster than regex.

Easiest way to remove all whitespace from a code file?

I'm participating in one of the Code Golf competitions where the smaller your file size is, the better.
Rather than manually removing all whitespace, etc., I'm looking for a program or website which will take a file, remove all whitespace (including new lines) and return a compact version of the file. Any ideas?
You could use:
sed 's/\s\s+/ /g' youfile > yourpackedfile`
There is also this online tool.
You can even do it in PHP (how marvelous is life):
$data = file_get_contents('foobar.php');
$data = preg_replace('/\s\s+/', ' ', $data);
file_put_contents('foobar2.php', $data);
You have to note this won't take care of a string variable like $bar = ' asd aa a'; it might be a problem depending on what you are doing. The online tool seems to handle this properly.
$ tr -d ' \n' <oldfile >newfile
In PowerShell (v2) this can be done with the following little snippet:
(-join(gc my_file))-replace"\s"
or longer:
(-join (Get-Content my_file)) -replace "\s"
It will join all lines together and remove all spaces and tabs.
However, for some languages you probably don't want to do that. In PowerShell for example you don't need semicolons unless you put multiple statements on a single line so code like
while (1) {
"Hello World"
$x++
}
would become
while(1){"HelloWorld"$x++}
when applying aforementioned statements naïvely. It both changed the meaning and the syntactical correctness of the program. Probably not too much to look out for in numerical golfed solutions but the issue with lines joined together still remains, sadly. Just putting a semicolon between each line doesn't actually help either.
This is a PHP function that will do the work for you:
function compress_php_src($src) {
// Whitespaces left and right from this signs can be ignored
static $IW = array(
T_CONCAT_EQUAL, // .=
T_DOUBLE_ARROW, // =>
T_BOOLEAN_AND, // &&
T_BOOLEAN_OR, // ||
T_IS_EQUAL, // ==
T_IS_NOT_EQUAL, // != or <>
T_IS_SMALLER_OR_EQUAL, // <=
T_IS_GREATER_OR_EQUAL, // >=
T_INC, // ++
T_DEC, // --
T_PLUS_EQUAL, // +=
T_MINUS_EQUAL, // -=
T_MUL_EQUAL, // *=
T_DIV_EQUAL, // /=
T_IS_IDENTICAL, // ===
T_IS_NOT_IDENTICAL, // !==
T_DOUBLE_COLON, // ::
T_PAAMAYIM_NEKUDOTAYIM, // ::
T_OBJECT_OPERATOR, // ->
T_DOLLAR_OPEN_CURLY_BRACES, // ${
T_AND_EQUAL, // &=
T_MOD_EQUAL, // %=
T_XOR_EQUAL, // ^=
T_OR_EQUAL, // |=
T_SL, // <<
T_SR, // >>
T_SL_EQUAL, // <<=
T_SR_EQUAL, // >>=
);
if(is_file($src)) {
if(!$src = file_get_contents($src)) {
return false;
}
}
$tokens = token_get_all($src);
$new = "";
$c = sizeof($tokens);
$iw = false; // Ignore whitespace
$ih = false; // In HEREDOC
$ls = ""; // Last sign
$ot = null; // Open tag
for($i = 0; $i < $c; $i++) {
$token = $tokens[$i];
if(is_array($token)) {
list($tn, $ts) = $token; // tokens: number, string, line
$tname = token_name($tn);
if($tn == T_INLINE_HTML) {
$new .= $ts;
$iw = false;
}
else {
if($tn == T_OPEN_TAG) {
if(strpos($ts, " ") || strpos($ts, "\n") || strpos($ts, "\t") || strpos($ts, "\r")) {
$ts = rtrim($ts);
}
$ts .= " ";
$new .= $ts;
$ot = T_OPEN_TAG;
$iw = true;
} elseif($tn == T_OPEN_TAG_WITH_ECHO) {
$new .= $ts;
$ot = T_OPEN_TAG_WITH_ECHO;
$iw = true;
} elseif($tn == T_CLOSE_TAG) {
if($ot == T_OPEN_TAG_WITH_ECHO) {
$new = rtrim($new, "; ");
} else {
$ts = " ".$ts;
}
$new .= $ts;
$ot = null;
$iw = false;
} elseif(in_array($tn, $IW)) {
$new .= $ts;
$iw = true;
} elseif($tn == T_CONSTANT_ENCAPSED_STRING
|| $tn == T_ENCAPSED_AND_WHITESPACE)
{
if($ts[0] == '"') {
$ts = addcslashes($ts, "\n\t\r");
}
$new .= $ts;
$iw = true;
} elseif($tn == T_WHITESPACE) {
$nt = #$tokens[$i+1];
if(!$iw && (!is_string($nt) || $nt == '$') && !in_array($nt[0], $IW)) {
$new .= " ";
}
$iw = false;
} elseif($tn == T_START_HEREDOC) {
$new .= "<<<S\n";
$iw = false;
$ih = true; // in HEREDOC
} elseif($tn == T_END_HEREDOC) {
$new .= "S;";
$iw = true;
$ih = false; // in HEREDOC
for($j = $i+1; $j < $c; $j++) {
if(is_string($tokens[$j]) && $tokens[$j] == ";") {
$i = $j;
break;
} else if($tokens[$j][0] == T_CLOSE_TAG) {
break;
}
}
} elseif($tn == T_COMMENT || $tn == T_DOC_COMMENT) {
$iw = true;
} else {
if(!$ih) {
$ts = strtolower($ts);
}
$new .= $ts;
$iw = false;
}
}
$ls = "";
}
else {
if(($token != ";" && $token != ":") || $ls != $token) {
$new .= $token;
$ls = $token;
}
$iw = true;
}
}
return $new;
}
// This is an example
$src = file_get_contents('foobar.php');
file_put_contents('foobar3.php',compress_php_src($src));
If your code editor programs supports regular expressions, you can try this:
Find this: [\r\n]{2,}
Replace with this: \n
Then Replace All
Notepad++ is quite a nice editor if you are on Windows, and it has a lot of predefined macros, trimming down code and removing whitespace among them.
It can do regular expressions and has a plethora of features to help the code hacker or script kiddie.
Notepad++ website
Run php -w on it!
php -w myfile.php
Unlike a regular expression, this is smart enough to leave strings alone, and it removes comments too.

Categories