1

I found in this site a very basic javascript function to encode text. Looking at the source code this is the string replacement code:

txtEscape = txtEscape.replace(/%/g,'@');

So the string stackoverflow becomes @73@74@61@63@6B@6F@76@65@72@66@6C@6F@77

I need a function that does the same elementary encryption in php, but I really don't understand what the /%/g does. I think in php the same function would be something like:

str_replace(/%/g,"@","stackoverflow");

But of course the /%/g doesn't work

1
  • .replace(/%/g,'@'); only replaces % characters with @, so it does nothing for the stackoverflow string. You should post the rest of your js in order to trace down what's doing the trick. :) Commented Feb 3, 2017 at 16:52

1 Answer 1

1

Replace a character

Indeed, the PHP function is str_replace (there are many functions for replacements). But, the regex expression is not the same :)

See official documentation: http://php.net/manual/en/function.str-replace.php

In your case, you want to replace a letter % by @.

g is a regex flag. And // are delimiter to activate the regex mode :)

The "g" flag indicates that the regular expression should be tested against all possible matches in a string. Without the g flag, it'll only test for the first.

<?php
echo str_replace('%', '@', '%73%74%61%63%6B%6F%76%65%72%66%6C%6F%77');
?>

In PHP, you can use flags with regex: preg_replace & cie.

Escape

See this post: PHP equivalent for javascript escape/unescape There are two functions stringToHex and hexToString to do what you want :)

Indeed, the site you provided use espace function to code the message:

document.write(unescape(str.replace(/@/g,'%')));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help, I've tried your script but what it only replaces % with @ in a string. The script in the site replaces the letter 'a' with '@61', the symbol '%' with '@25' and so on, that's what the php script should do
I edited my previous reply with a solution for the escaping issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.