Related
I am trying to replace every question mark "?" in a string with a values in an array.
I need to go through a string, and replace the first occurrence of '?' in the string with a value. I would need to do that for every occurrence
Here is what I tried
function sprintf2($str='', array $values = array(), $char = '?')
{
if (!$str){
return '';
}
if (count($values) > 0)
{
foreach ($values as $value)
{
$str = preg_replace('/'. $char . '/', $value, $str, 1);
}
}
echo $str;
}
But I am getting the following exception
preg_replace(): Compilation failed: nothing to repeat at offset 0
The following shows how I am calling the function
$bindings = array(10, 500);
$str = "select * from `survey_interviews` where `survey_id` = ? and `call_id` = ? limit 1";
sprintf2($str, $bindings);
What am I doing wrong here? why do I get this exception?
Use str_replace instead of preg_replace, since you're replacing a literal string, not a regular expression pattern.
However, str_replace always replaces all matches, there's no way to limit it to just the first match (preg_replace is similar). The 4th argument is not a limit, it's a variable that gets set to the number of matches that were found and replaced. To replace just one match, you can combine strpos and substr_replace:
function sprintf2($str='', array $values = array(), $char = '?')
{
if (!$str){
return '';
}
if (count($values) > 0)
{
$len = strlen($char);
foreach ($values as $value)
{
$pos = strpos($str, $char);
if ($pos !== false) {
$str = substr_replace($str, $value, $pos, strlen($char));
}
}
}
echo $str;
}
DEMO
You need to escape the '?' sign in your regexp using a backslash ( '\?' instead of '?').
But your code can be easily refactored to use preg_replace_callback instead:
$params = array(1, 3);
$str = '? bla ?';
echo preg_replace_callback('#\?#', function() use (&$params) {
return array_pop($params);
}, $str);
Hope this code helps you.
function sprintf2($string = '', array $values = array(), $char = '?')
{
if (!$string){
return '';
}
if (count($values) > 0)
{
$exploded = explode($char, $string);
$i = 0;
$string = '';
foreach ($exploded as $segment) {
if( $i < count($values)){
$string .= ($segment . $values[$i]);
++$i;
}
}
}
echo $string;
}
$bindings = array(10, 500);
$str = "select * from `survey_interviews` where `survey_id` = ? and `call_id`= ? limit 1";
echo sprintf2($str, $bindings);
Explanation:
In your code, you're using the preg_match and the first parameter in the preg_match method is a regex pattern. what you're trying to replace is ? has a valid meaning for 0 or 1 CHARACTER. So, you've to escape that by doing \?. Though all the characters are not needed to be escaped, so, for making your method work, you've to check the character that are valid for any regex.
In my code, I've split the string for the character you want. then appending the values at the end of the part what we get from the array. and this should be done till the values length of the value array, otherwise the offset error will occur.
I would like to rename all variables within the file to random name.
For example this:
$example = "some $string";
function ($variable2) {
echo $variable2;
}
foreach ($variable3 as $key => $var3val) {
echo $var3val . "somestring";
}
Will become this:
$frk43r = "some $string";
function ($izi34ee) {
echo $izi34ee;
}
foreach ($erew7er as $iure7 => $er3k2) {
echo $er3k2 . "some$string";
}
It doesn't look so easy task so any suggestions will be helpful.
I would use token_get_all to parse the document and map a registered random string replacement on all interesting tokens.
To obfuscate all the variable names, replace T_VARIABLE in one pass, ignoring all the superglobals.
Additionally, for the bounty's requisite function names, replace all the T_FUNCTION declarations in the first pass. Then a second pass is needed to replace all the T_STRING invocations because PHP allows you to use a function before it's declared.
For this example, I generated all lowercase letters to avoid case-insensitive clashes to function names, but you can obviously use whatever characters you want and add an extra conditional check for increased complexity. Just remember that they can't start with a number.
I also registered all the internal function names with get_defined_functions to protect against the extremely off-chance possibility that a randomly generated string would match one of those function names. Keep in mind this won't protect against special extensions installed on the machine running the obfuscated script that are not present on the server obfuscating the script. The chances of that are astronomical, but you can always ratchet up the length of the randomly generated string to diminish those odds even more.
<?php
$tokens = token_get_all(file_get_contents('example.php'));
$globals = array(
'$GLOBALS',
'$_SERVER',
'$_GET',
'$_POST',
'$_FILES',
'$_COOKIE',
'$_SESSION',
'$_REQUEST',
'$_ENV',
);
// prevent name clashes with randomly generated strings and native functions
$registry = get_defined_functions();
$registry = $registry['internal'];
// first pass to change all the variable names and function name declarations
foreach($tokens as $key => $element){
// make sure it's an interesting token
if(!is_array($element)){
continue;
}
switch ($element[0]) {
case T_FUNCTION:
$prefix = '';
// this jumps over the whitespace to get the function name
$index = $key + 2;
break;
case T_VARIABLE:
// ignore the superglobals
if(in_array($element[1], $globals)){
continue 2;
}
$prefix = '$';
$index = $key;
break;
default:
continue 2;
}
// check to see if we've already registered it
if(!isset($registry[$tokens[$index][1]])){
// make sure our random string hasn't already been generated
// or just so crazily happens to be the same name as an internal function
do {
$replacement = $prefix.random_str(16);
} while(in_array($replacement, $registry));
// map the original and register the replacement
$registry[$tokens[$index][1]] = $replacement;
}
// rename the variable
$tokens[$index][1] = $registry[$tokens[$index][1]];
}
// second pass to rename all the function invocations
$tokens = array_map(function($element) use ($registry){
// check to see if it's a function identifier
if(is_array($element) && $element[0] === T_STRING){
// make sure it's one of our registered function names
if(isset($registry[$element[1]])){
// rename the variable
$element[1] = $registry[$element[1]];
}
}
return $element;
},$tokens);
// dump the tokens back out to rebuild the page with obfuscated names
foreach($tokens as $token){
echo $token[1] ?? $token;
}
/**
* https://stackoverflow.com/a/31107425/4233593
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* #param int $length How many characters do we want?
* #param string $keyspace A string of all possible characters
* to select from
* #return string
*/
function random_str($length, $keyspace = 'abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
Given this example.php
<?php
$example = 'some $string';
if(isset($_POST['something'])){
echo $_POST['something'];
}
function exampleFunction($variable2){
echo $variable2;
}
exampleFunction($example);
$variable3 = array('example','another');
foreach($variable3 as $key => $var3val){
echo $var3val."somestring";
}
Produces this output:
<?php
$vsodjbobqokkaabv = 'some $string';
if(isset($_POST['something'])){
echo $_POST['something'];
}
function gkfadicwputpvroj($zwnjrxupprkbudlr){
echo $zwnjrxupprkbudlr;
}
gkfadicwputpvroj($vsodjbobqokkaabv);
$vfjzehtvmzzurxor = array('example','another');
foreach($vfjzehtvmzzurxor as $riuqtlravsenpspv => $mkdgtnpxaqziqkgo){
echo $mkdgtnpxaqziqkgo."somestring";
}
EDIT 4.12.2016 - please see below! (after first answer)
I've just tried to find a solution which can handle both cases: your given case and this example from Elias Van Ootegerm.
of course it should be improved as mentioned in one of my comments, but it works for your example:
$source = file_get_contents("source.php");
// this should get all Variables BUT isn't right at the moment if a variable is followed by an ' or " !!
preg_match_all('/\$[\$a-zA-Z0-9\[\'.*\'\]]*/', $source, $matches);
$matches = array_unique($matches[0]);
// this array saves all old and new variable names to track all replacements
$replacements = array();
$obfuscated_source = $source;
foreach($matches as $varName)
{
do // generates random string and tests if it already is used by an earlier replaced variable name
{
// generate a random string -> should be improved.
$randomName = substr(md5(rand()), 0, 7);
// ensure that first part of variable name is a character.
// there could also be a random character...
$randomName = "a" . $randomName;
}
while(in_array("$" . $randomName, $replacements));
if(substr($varName, 0,8) == '$GLOBALS')
{
// this handles the case of GLOBALS variables
$delimiter = substr($varName, 9, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$GLOBALS[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,8) == '$_SERVER')
{
// this handles the case of SERVER variables
$delimiter = substr($varName, 9, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_SERVER[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,5) == '$_GET')
{
// this handles the case of GET variables
$delimiter = substr($varName, 6, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_GET[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,6) == '$_POST')
{
// this handles the case of POST variables
$delimiter = substr($varName, 7, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_POST[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,7) == '$_FILES')
{
// this handles the case of FILES variables
$delimiter = substr($varName, 8, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_FILES[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,9) == '$_REQUEST')
{
// this handles the case of REQUEST variables
$delimiter = substr($varName, 10, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_REQUEST[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,9) == '$_SESSION')
{
// this handles the case of SESSION variables
$delimiter = substr($varName, 10, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_SESSION[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,5) == '$_ENV')
{
// this handles the case of ENV variables
$delimiter = substr($varName, 6, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_ENV[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 0,8) == '$_COOKIE')
{
// this handles the case of COOKIE variables
$delimiter = substr($varName, 9, 1);
if($delimiter == '$') $delimiter = '';
$newName = '$_COOKIE[' .$delimiter . $randomName . $delimiter . ']';
}
else if(substr($varName, 1, 1) == '$')
{
// this handles the case of variable variables
$name = substr($varName, 2, strlen($varName)-2);
$pattern = '/(?=\$)\$' . $name . '.*;/';
preg_match_all($pattern, $source, $varDeclaration);
$varDeclaration = $varDeclaration[0][0];
preg_match('/\s*=\s*["\'](?:\\.|[^"\\]])*["\']/', $varDeclaration, $varContent);
$varContent = $varContent[0];
preg_match('/["\'](?:\\.|[^"\\]])*["\']/', $varContent, $varContentDetail);
$varContentDetail = substr($varContentDetail[0], 1, strlen($varContentDetail[0])-2);
$replacementDetail = str_replace($varContent, substr($replacements["$" . $varContentDetail], 1, strlen($replacements["$" . $varContentDetail])-1), $varContent);
$explode = explode($varContentDetail, $varContent);
$replacement = $explode[0] . $replacementDetail . $explode[1];
$obfuscated_source = str_replace($varContent, $replacement, $obfuscated_source);
}
else
{
$newName = '$' . $randomName;
}
$obfuscated_source = str_replace($varName, $newName, $obfuscated_source);
$replacements[$varName] = $newName;
}
// this part may be useful to change hard-coded returns of functions.
// it changes all remaining words in the document which are like the previous changed variable names to the new variable names
// attention: if the variables in the document have common names it could also change text you don't like to change...
foreach($replacements as $before => $after)
{
$name_before = str_replace("$", "", $before);
$name_after = str_replace("$", "", $after);
$obfuscated_source = str_replace($name_before, $name_after, $obfuscated_source);
}
// here you can place code to write back the obfuscated code to the same or to a new file, e.g:
$file = fopen("result.php", "w");
fwrite($file, $obfuscated_source);
fclose($file);
EDIT there are still some cases left which require some effort.
At least some kinds of variable declarations may not be handled correctly!
Also the first regex is not perfect, my current status is like:
'/\$\$?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/'
but this does not get the index-values of predefined variables... But I think it has some potential. If you use it like here you get all 18 involved variables... The next step could be to determine if a [..] follws after the variable name. If so any predefined variable AND such cases like $g = $GLOBALS; and any further use of such a $g would be covered...
EDIT 4.12.2016
due to LSerni and several comments on both the original quesion and some solutions I also wrote a parsing solution which you can find below.
It handles an extended example file which was my aim. If you find any other challenge, please tell me!
new solution:
$variable_names_before = array();
$variable_names_after = array();
$function_names_before = array();
$function_names_after = array();
$forbidden_variables = array(
'$GLOBALS',
'$_SERVER',
'$_GET',
'$_POST',
'$_FILES',
'$_COOKIE',
'$_SESSION',
'$_REQUEST',
'$_ENV',
);
$forbidden_functions = array(
'unlink'
);
// read file
$data = file_get_contents("example.php");
$lock = false;
$lock_quote = '';
for($i = 0; $i < strlen($data); $i++)
{
// check if there are quotation marks
if(($data[$i] == "'" || $data[$i] == '"'))
{
// if first quote
if($lock_quote == '')
{
// remember quotation mark
$lock_quote = $data[$i];
$lock = true;
}
else if($data[$i] == $lock_quote)
{
$lock_quote = '';
$lock = false;
}
}
// detect variables
if(!$lock && $data[$i] == '$')
{
$start = $i;
// detect variable variable names
if($data[$i+1] == '$')
{
$start++;
// increment $i to avoid second detection of variable variable as "normal variable"
$i++;
}
$end = 1;
// find end of variable name
while(ctype_alpha($data[$start+$end]) || is_numeric($data[$start+$end]) || $data[$start+$end] == "_")
{
$end++;
}
// extract variable name
$variable_name = substr($data, $start, $end);
if($variable_name == '$')
{
continue;
}
// check if variable name is allowed
if(in_array($variable_name, $forbidden_variables))
{
// forbidden variable deteced, do whatever you want!
}
else
{
// check if variable name already has been detected
if(!in_array($variable_name, $variable_names_before))
{
$variable_names_before[] = $variable_name;
// generate random name for variable
$new_variable_name = "";
do
{
$new_variable_name = random_str(rand(5, 20));
}
while(in_array($new_variable_name, $variable_names_after));
$variable_names_after[] = $new_variable_name;
}
//var_dump("variable: " . $variable_name);
}
}
// detect function-definitions
// the third condition checks if the symbol before 'function' is neither a character nor a number
if(!$lock && strtolower(substr($data, $i, 8)) == 'function' && (!ctype_alpha($data[$i-1]) && !is_numeric($data[$i-1])))
{
// find end of function name
$end = strpos($data, '(', $i);
// extract function name and remove possible spaces on the right side
$function_name = rtrim(substr($data, ($i+9), $end-$i-9));
// check if function name is allowed
if(in_array($function_name, $forbidden_functions))
{
// forbidden function detected, do whatever you want!
}
else
{
// check if function name already has been deteced
if(!in_array($function_name, $function_names_before))
{
$function_names_before[] = $function_name;
// generate random name for variable
$new_function_name = "";
do
{
$new_function_name = random_str(rand(5, 20));
}
while(in_array($new_function_name, $function_names_after));
$function_names_after[] = $new_function_name;
}
//var_dump("function: " . $function_name);
}
}
}
// this array contains prefixes and suffixes for string literals which
// may contain variable names.
// if string literals as a return of functions should not be changed
// remove the last two inner arrays of $possible_pre_suffixes
// this will enable correct handling of situations like
// - $func = 'getNewName'; echo $func();
// but it will break variable variable names like
// - ${getNewName()}
$possible_pre_suffixes = array(
array(
"prefix" => "= '",
"suffix" => "'"
),
array(
"prefix" => '= "',
"suffix" => '"'
),
array(
"prefix" => "='",
"suffix" => "'"
),
array(
"prefix" => '="',
"suffix" => '"'
),
array(
"prefix" => 'rn "', // return " ";
"suffix" => '"'
),
array(
"prefix" => "rn '", // return ' ';
"suffix" => "'"
)
);
// replace variable names
for($i = 0; $i < count($variable_names_before); $i++)
{
$data = str_replace($variable_names_before[$i], '$' . $variable_names_after[$i], $data);
// try to find strings which equals variable names
// this is an attempt to handle situations like:
// $a = "123";
// $b = "a"; <--
// $$b = "321"; <--
// and also
// function getName() { return "a"; }
// echo ${getName()};
$name = substr($variable_names_before[$i], 1);
for($j = 0; $j < count($possible_pre_suffixes); $j++)
{
$data = str_replace($possible_pre_suffixes[$j]["prefix"] . $name . $possible_pre_suffixes[$j]["suffix"],
$possible_pre_suffixes[$j]["prefix"] . $variable_names_after[$i] . $possible_pre_suffixes[$j]["suffix"],
$data);
}
}
// replace funciton names
for($i = 0; $i < count($function_names_before); $i++)
{
$data = str_replace($function_names_before[$i], $function_names_after[$i], $data);
}
/**
* https://stackoverflow.com/a/31107425/4233593
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* #param int $length How many characters do we want?
* #param string $keyspace A string of all possible characters
* to select from
* #return string
*/
function random_str($length, $keyspace = 'abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i)
{
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
example input file:
$example = 'some $string';
$test = '$abc 123' . $example . '$hello here I "$am"';
if(isset($_POST['something'])){
echo $_POST['something'];
}
function exampleFunction($variable2){
echo $variable2;
}
exampleFunction($example);
$variable3 = array('example','another');
foreach($variable3 as $key => $var3val){
echo $var3val."somestring";
}
$test = "example";
$$test = 'hello';
exampleFunction($example);
exampleFunction($$test);
function getNewName()
{
return "test";
}
exampleFunction(${getNewName()});
output of my function:
$fesvffyn = 'some $string';
$zimskk = '$abc 123' . $fesvffyn . '$hello here I "$am"';
if(isset($_POST['something'])){
echo $_POST['something'];
}
function kainbtqpybl($yxjvlvmyfskwqcevo){
echo $yxjvlvmyfskwqcevo;
}
kainbtqpybl($fesvffyn);
$lmiphctfgjfdnonjpia = array('example','another');
foreach($lmiphctfgjfdnonjpia as $qypdfcpcla => $gwlpcpnvnhbvbyflr){
echo $gwlpcpnvnhbvbyflr."somestring";
}
$zimskk = "fesvffyn";
$$zimskk = 'hello';
kainbtqpybl($fesvffyn);
kainbtqpybl($$zimskk);
function tauevjkk()
{
return "zimskk";
}
kainbtqpybl(${tauevjkk()});
I know there are some cases left, where you can find an issue with variable variable names, but then you may have to expand the $possible_pre_suffixes array...
Maybe you also want to differentiate between global variables and "forbidden variables"...
Well, you can try write your own but the number of strange things you have to handle are likely to overwhelm you, and I presume you are more interested in using such a tool than writing and maintaining one yourself. (There a lots of broken PHP obfuscators out there, where people have tried to do this).
If you want one that is reliable, you do have base it on a parser or your tool will mis-parse the text and handle it wrong (this is the first "strange thing"). Regexes simply won't do the trick.
The Semantic Designs PHP Obfuscator (from my company), taken out of the box, took this slightly modified version of Elias Van Ootegem's example:
<?php
//non-obfuscated
function getVarname()
{//the return value has to change
return (('foobar'));
}
$format = '%s = %d';
$foobar = 123;
$variableVar = (('format'));//you need to change this string
printf($$variableVar, $variableVar = getVarname(), $$variableVar);
echo PHP_EOL;
var_dump($GLOBALS[(('foobar'))]);//note the key == the var
and produced this:
<?php function l0() { return (('O0')); } $l1="%\163 = %d"; $O1=0173; $l2=(('O2')); printf($$l2,$l2=l0(),$$l2); echo PHP_EOL; var_dump($GLOBALS[(('O0'))]);
The key issue in Elias's example are strings that actually contain variable names. In general, there is no way for a tool to know that "x" is a variable name, and not just the string containing the letter x. But, the programmers know. We insist that such strings be marked [by enclosing them in ((..)) ] and then the obfuscator can obfuscate their content properly.
Sometimes the string contains variables names and other things; it that case,
the programmer has to break up the string into "variable name" content and everything else. This is pretty easy to do in practice, and is
the "slight change" I made to his supplied code.
Other strings, not being marked, are left alone. You only have to do this
once to the source file. [You can say this is cheating, but no other practical answer will work; the tool cannot know reliably. Halting Problem, if you insist.].
The next thing to get right is reliable obfuscation across multiple files. You can't do this one file at a time. This obfuscator has been used on very big PHP applications (thousands of PHP script files).
Yes, it does use a full PHP parser. Not nikic's.
I ended up with this simple code:
$tokens = token_get_all($src);
$skip = array('$this','$_GET','$_POST','$_REQUEST','$_SERVER','$_COOKIE','$_SESSION');
function renameVars($tokens,$content,$skip){
$vars = array();
foreach($tokens as $token) {
if ($token[0] == T_VARIABLE && !in_array($token[1],$skip))
$vars[generateRandomString()]= $token[1];
}
$vars = array_unique($vars);
$vars2 = $vars;
foreach($vars as $new => $old){
foreach($vars2 as $var){
if($old!=$var && strpos($var,$old)!==false){
continue 2;
}
}
$content = str_replace($old,'${"'.$new.'"}',$content);
//function(${"example"}) will trigger error. This is why we need this:
$content = str_replace('(${"'.$new.'"}','($'.$new,$content);
$content = str_replace(',${"'.$new.'"}',',$'.$new,$content);
$chars = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
//for things like function deleteExpired(Varien_Event_Observer $fz5eDWIt1si), Exception,
foreach($chars as $char){
$content = str_replace($char.' ${"'.$new.'"}',$char.' $'.$new,$content);
}
}
It works for me because the code is simple. I guess it wont work in all scenarios.
I have it working now but there may still be some vulnerabilities because PHP allows functions names and variables names to be generated dynamically.
The first function replaces $_SESSION, $_POST etc. with functions:
function replaceArrayVariable($str, $arr, $function)
{
$str = str_replace($arr, $function, $str);
$lastPos = 0;
while (($lastPos = strpos($str, $function, $lastPos)) !== false)
{
$lastPos = $lastPos + strlen($function);
$currentPos = $lastPos;
$openSqrBrackets = 1;
while ($openSqrBrackets > 0)
{
if ($str[$currentPos] === '[')
$openSqrBrackets++;
elseif ($str[$currentPos] === ']')
$openSqrBrackets--;
$currentPos++;
}
$str[$currentPos - 1] = ')';
}
return $str;
}
The second renames functions ignoring whitelisted keywords:
function renameFunctions($str)
{
preg_match_all('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $str, $matches, PREG_OFFSET_CAPTURE);
$totalMatches = count($matches[0]);
$offset = 0;
for ($i = 0; $i < $totalMatches; $i++)
{
$matchIndex = $matches[0][$i][1] + $offset;
if ($matchIndex === 0 || $str[$matchIndex - 1] !== '$')
{
$keyword = $matches[0][$i][0];
if ($keyword !== 'true' && $keyword !== 'false' && $keyword !== 'if' && $keyword !== 'else' && $keyword !== 'getPost' && $keyword !== 'getSession')
{
$str = substr_replace($str, 'qq', $matchIndex, 0);
$offset += 2;
}
}
}
return $str;
}
Then to rename functions, variables, and non-whitelisted keywords, I use this code:
$str = replaceArrayVariable($str, '$_POST[', 'getPost(');
$str = replaceArrayVariable($str, '$_SESSION[', 'getSession(');
preg_match_all('/\'(?:\\\\.|[^\\\\\'])*\'|.[^\']+/', $str, $matches);
$str = '';
foreach ($matches[0] as $match)
{
if ($match[0] != "'")
{
$match = preg_replace('!\s+!', ' ', $match);
$match = renameFunctions($match);
$match = str_replace('$', '$qq', $match);
}
$str .= $match;
}
$search=array("<",">","!=","<=",">=")
$value="name >= vivek ";
I want to check if $value contains any of the values of the $search array. I can find out using foreach and the strpos function. Without resorting to using foreach, can I still find the answer? If so, kindly help me to solve this problem.
Explode $value and convert it into array and then use array_intersect() function in php to check if the string does not contain the value of the array.Use the code below
<?php
$search=array("<",">","!=","<=",">=");
$value='name >= vivek ';
$array = explode(" ",$value);
$p = array_intersect($search,$array);
$errors = array_filter($p);
//Check if the string is not empty
if(!empty($errors)){
echo "The string contains an value of array";
}
else
{
echo "The string does not containe the value of an array";
}
?>
Test the code here http://sandbox.onlinephpfunctions.com/code/7e65faf808de77036a83e185050d0895553d8211
Hope this helps you
Yes, but it will require you to re structure your code.
$search = array("<" => 0, ">" => 1,"!=" => 2,"<=" => 3,">=" => 4);
$value = "name => vivek ";
$value = explode(" ", $value);
foreach($value as $val) {
// search the array in O(1) time
if(isset($search[$val])) {
// found a match
}
}
Use array_map() and array_filter()
function cube($n)
{
$value="name => vivek ";
return strpos($value, $n);
//return($n * $n * $n);
}
$a = array("<",">","!=","<=",">=");
$value="name => vivek ";
$b = array_map("cube", $a);
print_r($b);
$b = array_filter($b);
print_r($b);
$search = array("<",">","!=","<=",">=");
$value="name => vivek ";
foreach($value as $searchval) {
if(strpos($value, $searchval) == false)
{
echo "match not found";
}
else
{
echo "match found";
}
}
Here's a solution using array_reduce:
<?PHP
function array_in_string_callback($carry, $item)
{
list($str, $found) = $carry;
echo $str . " - " . $found . " - " . $str . " - " . $item . "<br/>";
$found |= strpos($str, $item);
return array($str, (boolean) $found);
}
function array_in_string($haystack, $needle)
{
$retVal = array_reduce($needle, "array_in_string_callback", array($haystack, false));
return $retVal[1];
}
$search=array("<",">","!=","<=",">=");
$value="name >= vivek ";
var_dump(array_in_string($value, $search));
?>
My first inclination was to solve the problem with array_walk() and a callback, as follows:
<?php
$search=array("<",">","!=","<=",">=");
$value = "name >= vivek ";
function test($item, $key, $str)
{
if( strpos($str, $item) !== FALSE ) {
echo "$item found in \"$str\"\n";
}
}
array_walk($search, 'test', $value);
// output:
> found in "name >= vivek "
>= found in "name >= vivek "
Live demo: http://3v4l.org/6B0WX
While this solves the problem without a foreach loop, it answers the question with a "what" rather than a "yes/no" response. The following code directly answers the question and permits answering the "what" too, as follows:
<?php
function test($x)
{
$value="name >= vivek ";
return strpos($value, $x);
}
$search = array("<",">","!=","<=",">=");
$chars = array_filter( $search, "test" );
$count = count($chars);
echo "Are there any search chars? ", $answer = ($count > 0)? 'Yes, as follows: ' : 'No.';
echo join(" ",$chars);
// output:
Are there any search chars? Yes, as follows: > >=
Live demo: http://3v4l.org/WJQ5c
If the response had been negative, then the output is 'No.' followed by a blank space.
A key difference in this second solution compared to the first, is that in this case there is a return result that can be manipulated. If an element of the array matches a character in the string, then array_filter adds that element to $chars. The new array's element count answers the question and the array itself contains any matches, if one wishes to display them.
str_repeat(A, B) repeat string A, B times:
$string = "This is a " . str_repeat("test", 2) .
"! " . str_repeat("hello", 3) . " and Bye!";
// Return "This is a testtest! hellohellohello and Bye!"
I need reverse operation:
str_shrink($string, array("hello", "test"));
// Return "This is a test(x2)! hello(x3) and Bye!" or
// "This is a [test]x2! [hello]x3 and Bye!"
Best and efficient way for create str_shrink function?
Here are two versions that I could come up with.
The first uses a regular expression and replaces duplicate matches of the $needle string with a single $needle string. This is the most vigorously tested version and handles all possibilities of inputs successfully (as far as I know).
function str_shrink( $str, $needle)
{
if( is_array( $needle))
{
foreach( $needle as $n)
{
$str = str_shrink( $str, $n);
}
return $str;
}
$regex = '/(' . $needle . ')(?:' . $needle . ')+/i';
return preg_replace_callback( $regex, function( $matches) { return $matches[1] . '(x' . substr_count( $matches[0], $matches[1]) . ')'; }, $str);
}
The second uses string manipulation to continually replace occurrences of the $needle concatenated with itself. Note that this one will fail if $needle.$needle occurs more than once in the input string (The first one does not have this problem).
function str_shrink2( $str, $needle)
{
if( is_array( $needle))
{
foreach( $needle as $n)
{
$str = str_shrink2( $str, $n);
}
return $str;
}
$count = 1; $previous = -1;
while( ($i = strpos( $str, $needle.$needle)) > 0)
{
$str = str_replace( $needle.$needle, $needle, $str);
$count++;
$previous = $i;
}
if( $count > 1)
{
$str = substr( $str, 0, $previous) . $needle .'(x' . $count . ')' . substr( $str, $previous + strlen( $needle));
}
return $str;
}
See them both in action
Edit: I didn't realize that the desired output wanted to include the number of repetitions. I've modified my examples accordingly.
You can play around with tis one, not tested a lot though
function shrink($s, $parts, $mask = "%s(x%d)"){
foreach($parts as $part){
$removed = 0;
$regex = "/($part)+/";
preg_match_all($regex, $s, $matches, PREG_OFFSET_CAPTURE);
if(!$matches)
continue;
foreach($matches[0] as $m){
$offset = $m[1] - $removed;
$nb = substr_count($m[0], $part);
$counter = sprintf($mask, $part, $nb);
$s = substr($s, 0, $offset) . $counter . substr($s, $offset + strlen($m[0]));
$removed += strlen($m[0]) - strlen($part);
}
}
return $s;
}
I think you can try with:
<?php
$string = "This is a testtest! hellohellohello and Bye!";
function str_shrink($string, $array){
$tr = array();
foreach($array as $el){
$n = substr_count($string, $el);
$tr[$el] = $el.'(x'.$n.')';
$pattern[] = '/('.$el.'\(x'.$n.'\))+/i';
}
return preg_replace($pattern, '${1}', strtr($string,$tr));
}
echo $string;
echo '<br/>';
echo str_shrink($string,array('test','hello')); //This is a test(x2)! hello(x3) and Bye!
?>
I have a second version in order to works with strings:
<?php
$string = "This is a testtest! hellohellohello and Bye!";
function str_shrink($string, $array){
$tr = array();
$array = is_array($array) ? $array : array($array);
foreach($array as $el){
$sN = 'x'.substr_count($string, $el);
$tr[$el] = $el.'('.$sN.')';
$pattern[] = '/('.$el.'\('.$sN.'\))+/i';
}
return preg_replace($pattern, '${1}', strtr($string,$tr));
}
echo $string;
echo '<br/>';
echo str_shrink($string,array('test','hello')); //This is a test(x2)! hello(x3) and Bye!
echo '<br/>';
echo str_shrink($string,'test'); //This is a test(x2)! hellohellohello and Bye!
?>
I kept it short:
function str_shrink($haystack, $needles, $match_case = true) {
if (!is_array($needles)) $needles = array($needles);
foreach ($needles as $k => $v) $needles[$k] = preg_quote($v, '/');
$regexp = '/(' . implode('|', $needles) . ')+/' . ($match_case ? '' : 'i');
return preg_replace_callback($regexp, function($matches) {
return $matches[1] . '(x' . (strlen($matches[0]) / strlen($matches[1])) . ')';
}, $haystack);
}
The behavior of cases like str_shrink("aaa", array("a", "a(x3)")) is it returns "a(x3)", which I thought was more likely intended if you're specifying an array. For the other behavior, giving a result of "a(x3)(x1)", call the function with each needle individually.
If you don't want multiples of one to get "(x1)" change:
return $matches[1] . '(x' . (strlen($matches[0]) / strlen($matches[1])) . ')';
to:
$multiple = strlen($matches[0]) / strlen($matches[1]);
return $matches[1] . (($multiple > 1) ? '(x' . $multiple . ')' : '');
Here's a very direct, single-regex technique and you don't need to collect the words in the string in advance.
There will be some fringe cases to mitigate which are not represented in the sample input, but as for the general purpose of this task, I reckon this is the way that I'd script this in my project.
Match (and capture) any full word that is repeated one or more times.
Match the contiguous repetitions of the word.
Replace the fullstring match (substring of multiple words) with the captured first instance of the word.
Before returning the replacement string for re-insertion, add the desired formatting and calculate the number of repetitions by dividing the fullstring length by the captured string's length.
Code: (Demo)
$string = "This is a " . str_repeat("test", 2) .
"!\n" . str_repeat("hello", 3) . " and Bye!\n" .
"When I sleep, the thought bubble says " . str_repeat("zz", 3) . ".";
echo preg_replace_callback(
'~\b(\w+?)\1+\b~',
function($m) {
return "[{$m[1]}](" . (strlen($m[0]) / strlen($m[1])) . ")";
},
$string
);
Output:
This is a [test](2)!
[hello](3) and Bye!
When I sleep, the thought bubble says [z](6).
For a whitelist of needles, this adaptation to my above code does virtually the same job.
Code: (Demo)
function str_shrink($string, $needles) {
// this escaping is unnecessary if only working with alphanumeric characters
$needles = array_map(function($needle) {
return preg_quote($needle, '~');
}, $needles);
return preg_replace_callback(
'~\b(' . implode('|', $needles) . ')\1+\b~',
function($m) {
return "[{$m[1]}](" . (strlen($m[0]) / strlen($m[1])) . ")";
},
$string
);
}
echo str_shrink($string, ['test', 'hello']);
Output:
This is a [test](2)!
[hello](3) and Bye!
When I sleep, the thought bubble says zzzzzz.
Say I have the following loop in my view
foreach ($value as $row):
echo $row['name'] . ', ';
endforeach;
This outputs a string like this in my browser
Geddy, Lee, Neil, Peart, Alex,
I wonder if anyone can suggest a method to truncate this string at n characters, for example
Geddy, Lee, Ne...
Since the string is being output from the loop I am unsure how to wrap a truncate function around this foreach.
Thanks for helping!
sample truncate function
function truncate_text($text, $nbrChar, $append='...') {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $text;
}
Why not save the row values to a variable and truncate that variable and just echo that?
var $str = "";
foreach ($value as $row):
$str .= $row['name'] . ', ';
endforeach;
echo truncate_text($str, 'whatever');
First up, the foreach is not required. Second, we can then truncate it if required quite simply.
// Maximum length of the string; note that this does not include the '...'
$length = 20;
// This is PHP 5.3 only and converts the value array to an array of names
// $value = array_map(function ($f) { return $f["name"];}, $value);
// This is a PHP 5.2 way to do the array mapping
$value = array_map(create_function('$f', 'return $f["name"];'), $value);
$string = join(', ', $value);
$truncated = (strlen($string) > $length)
? substr($string, 0, $length) . '...'
: $string;
This also has the benefit of not leaving an ugly trailing comma.
function truncate_text($text, $nbrChar, $append='...') {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $text;
}
and then in the foreach you can do it like this
foreach ($value as $row) {
$name = truncate_text($row['name']);
}
now $name will output truncated text.
also consider using brackets for loops, or conditions, although it is not necessary but it will help you a lot while debugging the code as using brackets {} can indent your code properly.
You can do this with break
$limit = 20;
$str = '';
foreach ($value as $row) {
if ($str > $limit) {
$str .= substr($row, 0, $limit) . '...';
break;
}
$str .= "$row, ";
$limit -= strlen($row);
}
$str = rtrim($str, ', ');
The (minor) advantage of this is that you don't have to iterate through the entire row.