Format String for SEO friendly - javascript

I have a string like
Deser't - & Fest !
how to format this string is seo friendly like Desert-Fest.
In php I use the above function
function cleanString($str, $separator = "-"){
$q_separator = preg_quote($separator);
$trans = array(
'&.+?;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'('.$q_separator.')+' => $separator
);
$str = strip_tags($str);
foreach ($trans as $key => $val){
$str = preg_replace("#".$key."#i", $val, $str);
}
$str = strtolower($str);
return trim($str, $separator);
}
How to do this in Jquery?
Thanks.

Half of your solution is to HTML-decode the entities in the input. That can be done in JS like this, or jQuery like this.
From there you can use a regular expression to remove any characters from the resulting string that you don't want, like this:
function htmlDecode(input) {
var e = document.createElement('textarea');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
let input = "Deser't - & Fest !";
let output = htmlDecode(input);
output = output.replace(/[^a-z-]/gi, ''); // remove anything that isn't a-Z or -
console.log(output);

Related

Problem with data types. Trying to rewrite js class into php [duplicate]

In PHP, how do I convert:
$result = "abdcef";
into an array that's:
$result[0] = a;
$result[1] = b;
$result[2] = c;
$result[3] = d;
Edited
You will want to use str_split().
$result = str_split('abcdef');
http://us2.php.net/manual/en/function.str-split.php
Don't know if you're aware of this already, but you may not need to do anything (depending on what you're trying to do).
$string = "abcdef";
echo $string[1];
//Outputs "b"
So you can access it like an array without any faffing if you just need something simple.
You can use the str_split() function:
$value = "abcdef";
$array = str_split($value);
If you wish to divide the string into array values of different amounts you can specify the second parameter:
$array = str_split($value, 2);
The above will split your string into an array in chunks of two.
$result = "abcdef";
$result = str_split($result);
There is also an optional parameter on the str_split function to split into chunks of x characters.
best you should go for "str_split()", if there is need to manual Or basic programming,
$string = "abcdef";
$resultArr = [];
$strLength = strlen($string);
for ($i = 0; $i < $strLength; $i++) {
$resultArr[$i] = $string[$i];
}
print_r($resultArr);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
https://www.php.net/manual/en/function.str-split.php#refsect1-function.str-split-notes
str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.
Use mb_str_split() instead.
If you need multibyte support in an outdated version of PHP (a version below PHP7.4), then use preg_split() on an empty pattern with a unicode flag. There is no need to slow down the regex engine with a capture group.
Code: (Demo)
var_export(
preg_split('//u', 'abcåäö', 0, PREG_SPLIT_NO_EMPTY)
// or preg_split('/.\K/us', 'abcåäö', 0, PREG_SPLIT_NO_EMPTY)
// or preg_split('/\X\K/u', 'abcåäö', 0, PREG_SPLIT_NO_EMPTY)
);
For any versions of PHP from 7.4 or higher, just use the dedicated function mb_str_split().
mb_str_split('abcåäö')
Output:
array (
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'å',
4 => 'ä',
5 => 'ö',
)
As a warning to researchers using other answers on this page, if you use square brace syntax to access characters by their offset or you use str_split(), you will get broken results when dealing with multibyte characters.
For anyone doing thorough research, I should also mention the \X (unicode version of the dot) respects newline characters by default. \X is slightly different from . without the s modifier. Demo
var_export(preg_split('/.\K/u', "å\nä", 0, PREG_SPLIT_NO_EMPTY)); // element [1] has two characters in it!
echo "\n---\n";
var_export(preg_split('/.\K/us', "å\nä", 0, PREG_SPLIT_NO_EMPTY));
echo "\n---\n";
var_export(preg_split('/\X\K/u', "å\nä", 0, PREG_SPLIT_NO_EMPTY));
With the help of str_split function, you will do it.
Like below::
<?php
$result = str_split('abcdef',1);
echo "<pre>";
print_r($result);
?>
You can use the str_split() function
$array = str_split($string);
foreach ($array as $p){
echo $p . "<br />";
}
str_split() is not safe for multibyte characters.
mb_str_split() requires PHP 7.4+.
Try preg_split() for the rescuse:
$result = preg_split('/(.)/u', 'abcåäö', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
If you tried the above ways and did not get results, try the following method. It worked for my language (Persian and Arabic):
$result = [];
for ( $i = 0; $i < mb_strlen( $string ); ++ $i ) {
$result[] = mb_substr( $string, $i, 1, 'UTF-8' );
}
var_dump($result);

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);

similar function explode php in javascript?

I have problem when I want to separate my string in JavaScript, this is my code :
var str= 'hello.json';
str.slice(0,4); //output hello
str.slice(6,9); //output json
the problem is when i want to slice second string ('json') I should create another slice too.
I want to make this code more simple , is there any function in JavaScript like explode function in php ?
You can use split()
var str = 'hello.json';
var res = str.split('.');
document.write(res[0] + ' ' + res[1])
or use substring() and indexOf()
var str = 'hello.json';
document.write(
str.substring(0, str.indexOf('.')) + ' ' +
str.substring(str.indexOf('.') + 1)
)
The php example for explode:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
The Javascript equivalent (ES2015 style):
//Example 1
let pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
let pieces = pizza.split(" ");
console.log(pieces[0]);
console.log(pieces[1]);
//Example 2
let data = "foo:*:1023:1000::/home/foo:/bin/sh";
let user, pass, uid, gid, gecos, home, shell;
[user, pass, uid, gid, gecos, home, ...shell] = data.split(":");
console.log(user);
console.log(pass);

Replace all commas BUT the main function ones?

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;
}

Categories

Resources