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
Related
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;');
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;
}
I'm looking to add to a string's value based on the output for multiple if statements but I don't seem to be having much success. I've declared comp_string="" at the beginning of the script then tried += so that for each condition that is true it adds a section on.
For the code example below if I submitted the value of www.facebook.com and www.twitter.com I would like comp_string to return 'fb=www.facebook.com&tw=www.twitter.com'
How would I go about concatenating/adding the string together and how do I add the & if more than one link is provided. I could add it to each string for any value thats not blank, but would an & on the end of the url with nothing following mess things up?
if (facebook_url != "") {
comp_string += "fb="+facebook_url;
}
if (twitter_url != "") {
comp_string += "tw="+twitter_url;
}
alert(comp_string);
A simple approach would be to add each string to an array, then join the array elements to produce the end result you are looking for.
var params = [];
if (facebook_url !== "") {
params.push("fb=" + facebook_url);
}
if (twitter_url !== "") {
params.push("tw=" + twitter_url);
}
alert(params.join("&"));
Reference
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;
}
I have got a div with words seprated by a comma. How can i arrange them so there is four words per line?
edit: the words are dynamically generated
Use the <pre>...</pre> tag. The text will appear on the screen exactly the way you have formatted it.
Using jQuery to simplify access to the DOM:
var content = $('#mydiv').text(); // get current content from the page
var words = content.split(','); // break into words
for (var i = 3; i < words.length; i += 4) { // every fourth word (but not the first)
words[i] += '<br>'; // append <br>
}
content = words.join(' '); // and rejoin with spaces
$('#mydiv').html(content); // and put it back in the page
NB: I've used .html() to write the contents back out otherwise the <br> tags won't be rendered properly.
Use the BR tag after every four words. See http://www.w3.org/wiki/Html/Elements/br
If str contains the words, then:
var lines = str.match(/([^,]+,*){1,4}/g);
var output = lines === null ? '' : lines.join('<br>');
Example
If:
str = "a,b,c,d,e,f,g,h,i";
Then output will be:
"a,b,c,d,<br>e,f,g,h,<br>i"
Demo here.
Using jQuery, everthing is easier. jQuery is a bunch of tools written in JavaScript and it is all saved to a variable called $. You can call jQuery which will call the base JavaScript for you and make life easier.
Add this to the <head> of your web page
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
Add id="arrange" to your div. If you don't like the word arrange, you can use any word you like. Make sure there are no spaces and only letters, numbers, underscores.
<div class="arrange">One two three four one two three four</div>
Add this anywhere after the div that has the text
<script type="text/javascript">
$('div.arrange').each(function () { // For each div with the class="arrange"
var words = this.innerHTML.split(/,/) // Get an array of all the words (separated by comma)
var newHTML = '' // We will add the new contents of the div here.
for(var i = 0; i < words.length; i++) { // For every word
if(i != 0) {// If this is not the first word
if(i % 4 == 0) { // If this is the fourth word
newHTML += '<br/>' // Add a <br/>
} else {
newHTML += ',' // Add a comma
}
}
newHTML += words[i] // Add the word
}
this.innerHTML = newHTML
})
</script>
In this case, I am using jQuery to loop through each div with class="arrange"
You can see a live example here: http://jsfiddle.net/gf5wD/
This example automatically includes jQuery and automatically adds the JavaScript to the end.
You will probably eventually want to save the jquery file to servers you control. The script tag in your head will call the jquery servers which means if their site goes down, yours gets messed up.
Greetings user521180 I got you and i think this code will help
function arrangeDiv() {
var div = document.getElementById('div');
var divinnerHTMLAry = div.textContent.split(' ');
div.innerHTML = "";
var divNewinnerHTML = '';
var count = 0;
for (var i = 0; i < divinnerHTMLAry.length; i++) {
if (divinnerHTMLAry[i] != "" && divinnerHTMLAry[i] != "\n") {
divNewinnerHTML += divinnerHTMLAry[i] + " ";
count += 1;
if (count == 4) {
divNewinnerHTML += "<br />";
}
}
}
div.innerHTML = divNewinnerHTML;
}
Regards :)
edit : this is a PHP solution
Maybe something like that should be able to make what you want.
$string = 'a, b, c, d, e, f';
$array = explode(',', $string,);
foreach($array as $key => $word) {
print trim($word);
if ($key % 4 == 0) {
print '<br />';
}
}
If you get your word in an other way, just arrange the code so you can skip the explode() function.