When my scripts are done, I want to optimize/convert them to smaller size + its harder to get know what do the files even they are stolen.
$c = file_get_contents('source.php');
$newStr = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT'))
$commentTokens[] = T_DOC_COMMENT; // PHP 5
if (defined('T_ML_COMMENT'))
$commentTokens[] = T_ML_COMMENT; // PHP 4
$tokens = token_get_all($c);
foreach ($tokens as $token) {
if (is_array($token)) {
if (in_array($token[0], $commentTokens))
continue;
$token = $token[1];
}
$newStr .= $token;
}
$newStr = str_replace (chr(13), '', $newStr);
$newStr = str_replace (chr(10), '', $newStr);
$newStr = preg_replace('/\s+/', ' ', $newStr);
now $newStr contain the "compressed" stuff. Almost OK, but it kills to much white spaces. If there are white spaces in code like this:
if (true)
{
codeeee();
}
it converts to:
if (true)
{
codeeee();
}
and thats ok. But in case of this:
$a = ' var ';
it does:
$a = ' var ';
which is unwanted. How to do this optimize correctly? Are there any ideas? I almost thinking of renaming class names etc.
With help from this answer I was able to create this regex which trims all whitespace (including line breaks) down to single spaces, but preserves the whitespace between quotes (either ' or ")
preg_replace('/\G(?:"[^"]*"|\'[^\']*\'|[^"\'\s]+)*\K\s+/', ' ', $string);
Related
I have this code:
$words = ['mleko', 'masło'];
$words = explode(' ', $value); // create an array of words
foreach($words as $word) { //iterate through words
$word = preg_replace('/[^\w]/uis', '', $word);
if (in_array(mb_strtolower($word), $allergens)) {
$return .= "<b>" . $word . "</b> ";
} else {
$return .= $word . " ";
}
}
The above code works fine, but it deletes characters like:,. e.t.c.
How can I fix it? :)
Problem jest w podejściu jakie zastosowałeś. Nie tylko w linii
$word = preg_replace('/[^\w]/uis', '', $word);
which should be extended with the characters of the Polish alphabet (the range of the \w class is [a-zA-Z0-9_], remember to mention the range of lowercase and uppercase characters separately) like in this line
$word = preg_replace('/[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/uis', '', $word);
Moreover, I believe that the above line is used incorrectly. In my opinion, you should save the result of this operation in another variable as below
$rawWord = preg_replace('/[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/uis', '', $word);
Thanks to this, you have access to both the purified and the original value, which you can use in this way
if (in_array(mb_strtolower($rawWord), $allergens)) {
$return .= str_replace($rawWord, "<b>{$rawWord}</b> ", $word);
} else {
$return .= $word;
}
With this approach, however, you will still miss some characters. Even spaces that you filtered out with explode earlier. In my opinion, instead of concatenating a string, you should build an array and finally concatenate it with spaces. Complete code below.
$allergens = ['jogurt', 'jaja', 'żytni', "jogurt", "banan"];
$value = 'Chleb żytni, masło z mleka, jogurt naturalny z mleka, jaja, pieczeń rzymska z kaszą gryczaną.';
$returns = [];
$words = explode(' ', $value); // create an array of words
foreach($words as $word) { //iterate through words
$rawWord = preg_replace('/[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/uis', '', $word);
if (in_array(mb_strtolower($rawWord), $allergens)) {
$returns[] = str_replace($rawWord, "<b>{$rawWord}</b>", $word);
} else {
$returns[] = $word;
}
}
$return = implode(' ', $returns);
Look at this line
$returns[] = str_replace($rawWord, "<b>{$rawWord}</b>", $word);
Replaces the original word (containing the characters you want to ignore) with cleaned and bold version of the word. This keeps all characters (like commas) stuck to the word.
In the $return variable at the end you will get something like this
Chleb żytni, masło z mleka, jogurt naturalny z mleka, jaja, pieczeń rzymska z kaszą gryczaną.
Example String:
AAAAAA BBBBB CCCCCCC
Output:
AAAXXX BBXXX CCCCXXX
I need to hide every last 3 chars of words. I tried str_replace but I can't make it. Thanks for help
$replacement = "***";
if (stripos($name, ' ') !== false) {
$star = substr($name, 0, -3).$replacement;
}
I tried this but code only hide last word's 3 char. I need every word. Thanks
You need to split your string up, replace the last three characters, and then reassemble it.
$replacement = "***";
// break your string into an array based on the spaces
$temp = explode(' ', $name) ;
// our temporary name
$newName = '' ;
// loop through each part of the original name
foreach($temp as $section) {
// append our modified string along with a space
$newName .= substr($section, 0, -3).$replacement . ' ' ;
}
// set $name = $newName without the trailing space
$name = substr($newName,0,-1) ;
$replacement = "***";
$star = "";
$pieces = explode(" ", $name);
foreach ($pieces as $piece){
$star .= substr($piece, 0, -3).$replacement." ";
}
Try this function,
function replaceLastThreeChars($string){
$reversed_string = strrev($string);
$replaced_string = str_replace(substr($reversed_string,0,3),"XXX",$reversed_string);
return strrev($replaced_string);
}
If you have a sentence, then you can slice it using spaces and call to this function and finally recreate the sentence.
I have a search String: $str (Something like "test"), a wrap string: $wrap (Something like "|") and a text string: $text (Something like "This is a test Text").
$str is 1 Time in $text. What i want now is a function that will wrap $str with the wrap defined in $wrap and output the modified text (even if $str is more than one time in $text).
But it shall not output the whole text but just 1-2 of the words before $str and then 1-2 of the words after $str and "..." (Only if it isn`t the first or last word). Also it should be case insensitive.
Example:
$str = "Text"
$wrap = "<span>|</span>"
$text = "This is a really long Text where the word Text appears about 3 times Text"
Output would be:
"...long <span>Text</span> where...word <span>Text</span> appears...times <span>Text</span>"
My Code (Obviusly doesnt works):
$tempar = preg_split("/$str/i", $text);
if (count($tempar) <= 2) {
$result = "... ".substr($tempar[0], -7).$wrap.substr($tempar[1], 7)." ...";
} else {
$amount = substr_count($text, $str);
for ($i = 0; $i < $amount; $i++) {
$result = $result.".. ".substr($tempar[$i], -7).$wrap.substr($tempar[$i+1], 0, 7)." ..";
}
}
If you have a tipp or a solution dont hesitate to let me know.
I have taken your approach and made it more flexible. If $str or $wrap changes you could have escaping issues within the regex pattern so I have used preg_quote.
Note that I added $placeholder to make it clearer, but you can use $placeholder = "|" if you don't like [placeholder].
function wrapInString($str, $text, $element = 'span') {
$placeholder = "[placeholder]"; // The string that will be replaced by $str
$wrap = "<{$element}>{$placeholder}</{$element}>"; // Dynamic string that can handle more than just span
$strExp = preg_quote($str, '/');
$matches = [];
$matchCount = preg_match_all("/(\w+\s+)?(\w+\s+)?({$strExp})(\s+\w+)?(\s+\w+)?/i", $text, $matches);
$response = '';
for ($i = 0; $i < $matchCount; $i++) {
if (strlen($matches[1][$i])) {
$response .= '...';
}
if (strlen($matches[2][$i])) {
$response .= $matches[2][$i];
}
$response .= str_replace($placeholder, $matches[3][$i], $wrap);
if (strlen($matches[4][$i])) {
$response .= $matches[4][$i];
}
if (strlen($matches[5][$i]) && $i == $matchCount - 1) {
$response .= '...';
}
}
return $response;
}
$text = "text This is a really long Text where the word Text appears about 3 times Text";
string(107) "<span>text</span> This...long <span>text</span> where...<span>text</span> appears...times <span>text</span>"
To make the replacement case insensitive you can use the i regex option.
If I understand your question correct, just a little bit of implode and explode magic needed
$text = "This is a really long Text where the word Text appears about 3 times Text";
$arr = explode("Text", $text);
print_r(implode('<span>Text</span>', $arr));
If you specifically need to render the span tags using HTML, just write it that way
$arr = explode("Text", $text);
print_r(implode('<span>Text</span>', $arr));
Use patern below to get your word and 1-2 words before and after
/((\w+\s+){1,2}|^)text((\s+\w+){1,2}|$)/i
demo
In PHP code it can be:
$str = "Text";
$wrap = "<span>|</span>";
$text = "This is a really long Text where the word Text appears about 3 times Text";
$temp = str_replace('|', $str, $wrap); // <span>Text</span>
// find patern and 1-2 words before and after
// (to make it casesensitive, delete 'i' from patern)
if(preg_match_all('/((\w+\s+){1,2}|^)text((\s+\w+){1,2}|$)/i', $text, $match)) {
$res = array_map(function($x) use($str, $temp) { return '... '.str_replace($str, $temp, $x) . ' ...';}, $match[0]);
echo implode(' ', $res);
}
I am using regular expression for getting multiple patterns from a given string.
Here, I will explain you clearly.
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
The above is my code.
Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??
Now, I need a regular expression that gives me patterns like
about_us, about-us, aboutus as output if i give about us as input.
Is this possible to do.
Please help me in that.
Thanks in advance!
And finally, my answer is
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
You need to do a loop to handle multiple possible outputs :
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
You can try without regex:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
If you put special characters into an array:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
Also you can use just str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.
e.g.
preg_replace('/\W+/', '-', $string);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
I am not sure that regexes are the good tool for that. However you can simply define this kind of function:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
Matches any character that is not a word character
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
in case its just that... you would get problems if it's a longer string :)
I would like to explode this kind of string in PHP:
$foo = "foo.txt da\ code.txt bar.txt";
And I want to explode it to have:
["foo.txt", "da\ code.txt", "bar.txt"]
I know I can use preg_split but I don't see what to put as regular expression.
Could someone help me?
You could match on a positive look behind for any space preceded by alpha characters.
<?php
$foo = "foo.txt da\ code.txt bar.txt";
print_r(preg_split("/(?<=[a-zA-Z])\s/", $foo));
You could also use a negative lookbehind for the general case
<?php
$foo = "foo.txt da\ code.txt bar.txt something.mp3 other# 9asdf";
print_r(preg_split('/(?<!\\\\)\s/', $foo));
Here's a funky, non-regex "parser". All kinds of fun. What was the world like before regular expressions? I mean, it must have been work. ;)
<?php
$foo = "foo.txt da\ code.txt bar.txt";
$foos = array();
$char = 0;
$index = 0;
$lookback = '';
while ($char < strlen($foo)) {
$lookback = $foo{$char-4} . $foo{$char-3} . $foo{$char-2} . $foo{$char-1} . $foo{$char};
if ($lookback == '.txt ') $index++;
$foos[$index] .= $foo{$char++};
}
print_r(array_map('trim', $foos));
?>
http://codepad.org/XMfLemeg
You could use preg_split() but it is slow so if escaped space is your only problem a lot faster would be to do it as simply as:
$array1 = explode(' ', $list);
$array2 = [];
$appendNext = false;
foreach($array1 as $elem)
{
if ($appendNext)
{
array_push($array2, array_pop($array2) . ' ' . $elem);
}
else
{
$array2[] = $elem;
}
$appendNext = (substr($elem, -1) === '\\');
}
var_dump($array2);
If you really want to do it via regex here is a working solution:
print_r(preg_split("/(?<!\\\)\s/", $foo));
http://codepad.org/ngbDaxA3
but it will be slower than above