Replace all commas BUT the main function ones? - javascript

I am posting here because I've been searching for an answer for few hours already and lost many others more on trial and error on this website http://www.regexr.com/ for the best Regex possible.
I couldn't find anything to remove all commas but the first function ones.
#Quick Edit: I will always have the content of the function as a String on my php script, because I copy it from the file that originated the function call.
Here is an example:
MyClass::myFunction(
array_merge($params, ['a', 'b', 'c', 'd']),
array_merge(["p01"], ["s01", "s02", "s03"]),
oi("s04", "p02", "p03"),
[["p05", "p06", "p07"],],
[
oi(),
"p04",
["p05", "p06", "p07"],
oi("p08", "p09", "p10", ["s05", "s06", "s07"]),
],
[
"p04",
["p05", "p06", "p07"],
oi("p08", "p09", "p10", ["s05", "s06", "s07"]),
]
)
All I want is to replace all the commas but the myFunction ones ( The ones that separates it's params ).
I am already able to get all the content inside the myFunction brackets, so you don't have to deal with that.
#Edit: The reason I need this is because I developed a debug function for my project that shows exactly what variable/function/thing generated that code.
The oi() function is just a random function that is there for example purpose. On this case, it'll return an array with the parameters it received.
Here is how I do it:
Example:
$variable = 'This is a test variable. For the purpose os testing, 2 + 2 is ' . ( 2 + 2 );
MyClass::myFunction($variable);
After the function is executed, I get the function call params with debug_backtrace().
I copy the entire content of the called function from the file that executed it, so I get it as string.
I get only the content inside the function, removing the MyClass::myFunction( and the last ).
I explode the result by commas to get all the params of the function, but in that way, I explode the commas that I can't explode. I need a way to find which comma I need to explode.
Here is the final result of the example above ( As I can't post images, I'll type it ):
<pre>
<pre class="source">variable</pre>
<pre class="content"><small>string</small>'This is a test variable. For the purpose os testing, 2 + 2 is 4' <i>(length=63)</i></pre>
</pre>

Thanks for all the help.
I came up with my own solution. I hope it is useful for anyone.
public static function extractParams($text)
{
$firstOpen = '';
$close = ['(' => ')', '[' => ']', '"' => '"', '\'' => '\''];
$open = ['[', '(', '"', '\''];
$counter = 0;
$splittedString = str_split($text);
$p = '';
$param = [];
foreach ($splittedString as $char) {
$p .= $char;
if (!$firstOpen) {
if (in_array($char, $open)) {
$firstOpen = $char;
$counter = 1;
}
} else {
if ($char === $firstOpen && !in_array($char, ['"', '\''])) {
$counter += 1;
} elseif ($char === $close[$firstOpen]) {
$counter -= 1;
}
if ($counter === 0) {
$param[] = trim(ltrim($p, ','));
$p = '';
$firstOpen = '';
}
}
}
if ($param === []) {
$param[] = trim(ltrim($p, ','));
}
return $param;
}

Related

How to display short information in list content?

I have already made data in my database. It made from ckeditor5. It looks like here
The data mentions many tags and attributes. so... I just need to get the words inside tag p only. So I can display on my website. The example of the result is here:
Note: I just need to show 100 letters. And add '...' in the last sentence.
My last code looks like this:
function removeTags(str) {
if ((str === null) || (str === ''))
return false;
else
str = str.toString();
// Regular expression to identify HTML tags in
// the input string. Replacing the identified
// HTML tag with a null string.
return str.replace(/(<([^>]+)>)/ig, '');
}
<?php
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo '
<script>
document.write(removeTags(
'.$row['main_article'].'));
</script>';
}
?>
I found the solution. Here it is, and hopefully someone need this in future for his ckeditor content:
<p><?php
$str = strip_tags($row['main_article']);
$str = substr($str, 0, 200) . '...';
echo $str;
?></p>
For truncating text, you can use this function.
function truncateString(str, num) {
// str = character length
if (str.length <= num) {
return str
}
return str.slice(0, num) + '...'
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
Source: https://medium.com/#DylanAttal/truncate-a-string-in-javascript-41f33171d5a8

Is there a way to trim a string formula taken from JSON object and apply it using PHP variables? [duplicate]

I want to calculate math expression from a string. I have read that the solution to this is to use eval(). But when I try to run the following code:
<?php
$ma ="2+10";
$p = eval($ma);
print $p;
?>
It gives me the following error:
Parse error: syntax error, unexpected $end in
C:\xampp\htdocs\eclipseWorkspaceWebDev\MandatoryHandinSite\tester.php(4)
: eval()'d code on line 1
Does someone know the solution to this problem.
While I don't suggest using eval for this (it is not the solution), the problem is that eval expects complete lines of code, not just fragments.
$ma ="2+10";
$p = eval('return '.$ma.';');
print $p;
Should do what you want.
A better solution would be to write a tokenizer/parser for your math expression. Here's a very simple regex-based one to give you an example:
$ma = "2+10";
if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE){
$operator = $matches[2];
switch($operator){
case '+':
$p = $matches[1] + $matches[3];
break;
case '-':
$p = $matches[1] - $matches[3];
break;
case '*':
$p = $matches[1] * $matches[3];
break;
case '/':
$p = $matches[1] / $matches[3];
break;
}
echo $p;
}
Take a look at this..
I use this in an accounting system where you can write math expressions in amount input fields..
Examples
$Cal = new Field_calculate();
$result = $Cal->calculate('5+7'); // 12
$result = $Cal->calculate('(5+9)*5'); // 70
$result = $Cal->calculate('(10.2+0.5*(2-0.4))*2+(2.1*4)'); // 30.4
Code
class Field_calculate {
const PATTERN = '/(?:\-?\d+(?:\.?\d+)?[\+\-\*\/])+\-?\d+(?:\.?\d+)?/';
const PARENTHESIS_DEPTH = 10;
public function calculate($input){
if(strpos($input, '+') != null || strpos($input, '-') != null || strpos($input, '/') != null || strpos($input, '*') != null){
// Remove white spaces and invalid math chars
$input = str_replace(',', '.', $input);
$input = preg_replace('[^0-9\.\+\-\*\/\(\)]', '', $input);
// Calculate each of the parenthesis from the top
$i = 0;
while(strpos($input, '(') || strpos($input, ')')){
$input = preg_replace_callback('/\(([^\(\)]+)\)/', 'self::callback', $input);
$i++;
if($i > self::PARENTHESIS_DEPTH){
break;
}
}
// Calculate the result
if(preg_match(self::PATTERN, $input, $match)){
return $this->compute($match[0]);
}
// To handle the special case of expressions surrounded by global parenthesis like "(1+1)"
if(is_numeric($input)){
return $input;
}
return 0;
}
return $input;
}
private function compute($input){
$compute = create_function('', 'return '.$input.';');
return 0 + $compute();
}
private function callback($input){
if(is_numeric($input[1])){
return $input[1];
}
elseif(preg_match(self::PATTERN, $input[1], $match)){
return $this->compute($match[0]);
}
return 0;
}
}
I recently created a PHP package that provides a math_eval helper function. It does exactly what you need, without the need to use the potentially unsafe eval function.
You just pass in the string version of the mathematical expression and it returns the result.
$two = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten = math_eval('2 * 5');
$four = math_eval('8 / 2');
You can also pass in variables, which will be substituted if needed.
$ten = math_eval('a + b', ['a' => 7, 'b' => 3]);
$fifteen = math_eval('x * y', ['x' => 3, 'y' => 5]);
Link: https://github.com/langleyfoxall/math_eval
Using eval function is very dangerous when you can't control the string argument.
Try Matex for safe Mathematical formulas calculation.
Solved!
<?php
function evalmath($equation)
{
$result = 0;
// sanitize imput
$equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
// convert alphabet to $variabel
$equation = preg_replace("/([a-z])+/i", "\$$0", $equation);
// convert percentages to decimal
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
$equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation != "" ){
$result = #eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
echo $result;
// return $equation;
}
$a = 2;
$b = 3;
$c = 5;
$f1 = "a*b+c";
$f1 = str_replace("a", $a, $f1);
$f1 = str_replace("b", $b, $f1);
$f1 = str_replace("c", $c, $f1);
evalmath($f1);
/*if ( $equation != "" ){
$result = #eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
echo $result;*/
?>
This method has two major drawbacks:
Security, php script is being evaluated by the eval function. This is bad,
especially when the user wants to inject malicious code.
Complexity
I created this, check it out: Formula Interpreter
How does it work ?
First, create an instance of FormulaInterpreter with the formula and its parameters
$formulaInterpreter = new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]);
Use the execute() method to interpret the formula. It will return the result:
echo $formulaInterpreter->execute();
in a single line
echo (new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]))->execute();
Examples
# Formula: speed = distance / time
$speed = (new FormulaInterpreter("distance/time", ["distance" => 338, "time" => 5]))->execute() ;
echo $speed;
#Venezuela night overtime (ordinary_work_day in hours): (normal_salary * days_in_a_work_month)/ordinary_work_day
$parameters = ["normal_salary" => 21000, "days_in_a_work_month" => 30, "ordinary_work_day" => 8];
$venezuelaLOTTTArt118NightOvertime = (new FormulaInterpreter("(normal_salary/days_in_a_work_month)/ordinary_work_day", $parameters))->execute();
echo $venezuelaLOTTTArt118NightOvertime;
#cicle area
$cicleArea = (new FormulaInterpreter("3.1416*(radio*radio)", ["radio" => 10]))->execute();
echo $cicleArea;
About the formulas
It must contain at least two operands and an operator.
Operands' name could be in upper or lower case.
By now, math functions as sin, cos, pow… are not included. I'm working to include them.
If your formula is not valid, you will get an error message like: Error, your formula (single_variable) is not valid.
Parameters' values must be numeric.
You can improve it if you want to!
eval Evaluates the given code as PHP. Meaning that it will execute the given paremeter as a PHP piece of code.
To correct your code, use this :
$ma ="print (2+10);";
eval($ma);
Using eval function
protected function getStringArthmeticOperation($value, $deduct)
{
if($value > 0){
$operator = '-';
}else{
$operator = '+';
}
$mathStr = '$value $operator $deduct';
eval("\$mathStr = \"$mathStr\";");
$userAvailableUl = eval('return '.$mathStr.';');
return $userAvailableUl;
}
$this->getStringArthmeticOperation(3, 1); //2
Finding a sweetspot between the dangers of eval and the limitless calculation possibilities I suggest checking the input for only numbers, operators and brackets:
if (preg_match('/^[0-9\+\-\*\/\(\)\.]+$/', $mathString)) {
$value = eval('return
' . $mathString . ';');
} else {
throw new \Exception('Invalid calc() value: ' . $mathString);
}
It's still easy to use yet relatively save. And it can handle any basic math calulation like (10*(1+0,2)) which isn't possible with most of the mentioned solutions here.
An eval'd expression should end with ";"
Try this :
$ma ="2+10;";
$p = eval($ma);
print $p;
By the way, this is out of scope but the 'eval' function won't return the value of the expression. eval('2+10') won't return 12.
If you want it to return 12, you should eval('return 2+10;');

Similar function in JavaScript to convert string/number

I have a function in PHP that gets a number inserted into a text input and converts it to a float, with comma separator for decimals.
After that, the number is registered in the database.
Now, I need to make something with JavaScript (or jQuery), that does the same kind of convertion.
$num = $_POST['precoItem'];//get the input value
$precoAd = tofloat($num);//convert it to float
$precoFinal = number_format($precoAd, 2, ',', '');//remove any 'dots' or 'spaces'
The PHP function toFloat() is this one:
function tofloat($num) {
$dotPos = strrpos($num, '.');
$commaPos = strrpos($num, ',');
$sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
if (!$sep) {
return floatval(preg_replace("/[^0-9]/", "", $num));
}
return floatval(
preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
);
}
For example, the final number will not have dots or spaces, only commas: Ex.: 45354,85 (45.354,85)
My JS knowledge is limited. I tried using things like:
var n = +$precoFinal;
var n = Number($precoFinal);
var n = parseFloat($precoFinal);
Why people like to downvote so much... Are you really gonna say that my question didn't had any research? Rly?
Try this:
var str = '45.354,85';
var num = str.split(/[\s.]+/).join('');
num = parseFloat(num.replace(",","."));
console.log(num);

using forward slash as matching pattern in regex

i have a textarea where user types his codes and a div tag where it renders how it will be displayed on a webpage. I am using custom tags to format user codes like [b]bold text[/b] instead of <b>bold text </b> i am using string.replace() function to replace custom tag with original to tag preview user codes. But how can use forward slash(/) as matching pattern
i have already gone though couples of know method . i have tried
string.replace(/[\/b]/gi,"</b>");
string.replace(/[\x2Fb]/gi,"</b>");
string.replace(/[\x2F b]/gi,"</b>");
Here is code how i am really doing it in my project
//Helper Function
function $(id){
return document.getElementById(id);
}
//Helper Variables//
//Display Preview of question
function render(){//
var question_content = $("question_content").value;
//Sanitizing data//
var entitles = {//List of all Html entitles & custum entitles
'<':"<",
'>':">",
'\n':"<br>",
'[b]':"<b>",
'[/b]':"</b>",
'[i]':"<i>",
'[/i]':"</i>",
'[code]':"<code class='prettyprint'>",
'[/code]':"</code>"
}
question_content = question_content.replace(/<|>|\n|[b]|[\/b]/gi, function (html_ent){return entitles[html_ent];});
//question_content = question_content.replace(/'/, "</b>");
var preview = $("preview");
preview.innerHTML = question_content;
//prettyPrint();
}
Actually, the first approach would have worked if you didn't forget about escaping brackets:
string.replace(/\[\/b]/gi,"</b>");
Only the opening one should be escaped, though; regex engine is smart enough to differentiate between ] as a literal symbol and as a metasymbol (that closed that character class subexpression).
Overall, you can simplify your code by using something like this:
var codes = ['b', 'i', 'code'];
// here goes a little hack to enable special decoration for some elements
codes.code = 'class="prettyprint"';
var string = 'abc[b]abc[/b]da[code]s[/code][something]d';
string.replace(/\[(\/?)([a-z]+)]/gi, function(m, p1, p2) {
return codes.indexOf(p2) !== -1
? '<' + p1 + p2 + (!p1 && p2 in codes ? ' ' + codes[p2] : '') + '>'
: m
});
It's certainly possible to express the same algorithm with a dictionary (object), like this:
var decorators = {
b: '', i: '',
code: 'class="prettyprint"'
};
var string = 'abc[b]abc[/b]da[code]s[/code][something]d';
string.replace(/\[(\/?)([a-z]+)]/gi, function(m, p1, p2) {
return p2 in decorators
? '<' + p1 + p2 +
(!p1 && decorators[p2] ? ' ' + decorators[p2] : '') + '>'
: m;
});

Sanitizing a string in php and javascript

How to check if the string contains any tags <>. I need to sanitize my string from xss attacks or attacks like that.
I am looking for a function which can santize my string in javascript and php.
This is what I have for java script , please let me know if this is correct ?
function parseThisString(strcode) {
var scripts = new Array();
while(strcode.indexOf("<") > -1 || strcode.indexOf("</") > -1) {
var s = strcode.indexOf("<");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</", s);
var e_e = strcode.indexOf(">", e);
scripts.push(strcode.substring(s_e+1, e));
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
if (scripts.length > 0) { return 1; } else { return 0; }
}
Can you guys show me any solid string sanitizing function in php ? I found this answer but I didt know how to transilate this function to a single return with 0 or 1 (yes or no) .
What is the correct way to detect whether string inputs contain HTML or not?
Please help me here . Thanks.
You can escape any html tags using htmlspecialchars().
$string = htmlspecialchar($old_string);
You can remove all html tags from string using strip_tags().
$string = strip_tags($old_string);
But if you wanna know if there's html tags in the string, you can use this function, combinated with strip_tags().
function hasHTML($string) {
if ($string != strip_tags($string))
return true;
else
return false;
}

Categories

Resources