Let's say I have a string: something
When I escape it in JS I get this: %73%6F%6D%65%74%68%69%6E%67
so I can use this code in JS to decode it:
document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));
I need the escape function in PHP which will do the same (will encode something to : %73%6F%6D%65%74%68%69%6E%67)
How to do that ?
PHP:
rawurlencode("your funky string");
JS:
decodeURIComponent('your%20funky%20string');
Don't use escape as it is being deprecated.
rawurldecode('%73%6F%6D%65%74%68%69%6E%67');
Some clarification first:
Let's say I have a string: something
When I escape it in JS I get this: %73%6F%6D%65%74%68%69%6E%67
That's wrong. (Btw, the JS escape() function is deprecated. You should use encodeURIComponent() instead!)
so I can use this code in JS to decode it:
document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));
Yep, this will write "something" to the document (as escape(), also unescape() is deprecated; use decodeURIComponent() instead).
To your question:
I need the [snip] function in PHP which [snip] encode something to %73%6F%6D%65%74%68%69%6E%67
What you're looking for is the hexadecimal representation of charachters. So, to get the string "%73%6F%6D%65%74%68%69%6E%67" from the string "something", you would need:
<?php
function stringToHex($string) {
$hexString = '';
for ($i=0; $i < strlen($string); $i++) {
$hexString .= '%' . bin2hex($string[$i]);
}
return $hexString;
}
$hexString = stringToHex('something');
echo strtoupper($hexString); // %73%6F%6D%65%74%68%69%6E%67
Backwards:
function hexToString($hexString) {
return pack("H*" , str_replace('%', '', $hexString));
}
$string = hexToString('%73%6F%6D%65%74%68%69%6E%67');
echo $string; // something
Related
I need to replace some text in a string. I think an example can explain better:
[myFile.json]
{ "Dear":"newString1", "an example string":"newString2" }
[example.php]
$myString = "#Dear# name, this is #an example string#.";
function gimmeNewVal($myVal){
$obj = json_decode(file_get_contents('myFile.json'));
return $obj->$myVal;
}
echo gimmeNewVal("Dear"); // This print "newString1"
So, what I need is to find any strings between the '#' symbol and for each string found I need to replace using the gimmeNewVal() function.
I already tried with preg_* functions but I'm not very able with regex...
Thanks for your help
You can use preg_match_all to match all strings of type #somestring# using regex #([^#]+)# and then iterate over a for loop to do the replacement of each such found string in the original string to replace with the actual value from your function gimmeNewVal which returns the value from your given json.
Here is the PHP code for same,
$myString = "#Dear# name, this is #an example string#.";
function gimmeNewVal($myVal){ // I've replaced your function from this to make it practically runnable so you can revert this function as posted in your post
$obj = json_decode('{ "Dear":"newString1", "an example string":"newString2" }');
return $obj->$myVal;
}
preg_match_all('/#([^#]+)#/', $myString, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
echo $matches[1][$i].' --> '.gimmeNewVal($matches[1][$i])."\n";
$myString = preg_replace('/'.$matches[0][$i].'/',gimmeNewVal($matches[1][$i]), $myString);
}
echo "\nTransformed myString: ".$myString;
Prints the transformed string,
Dear --> newString1
an example string --> newString2
Transformed myString: newString1 name, this is newString2.
Let me know if this is what you wanted.
You can use preg_replace_callback function
$myString = "#Dear# name, this is #an example string#.";
$obj = json_decode(file_get_contents('myFile.json'));
echo preg_replace_callback('/#([^#]+)#/',
function ($x) use($obj) { return isset($obj->{$x[1]}) ? $obj->{$x[1]} : ''; },
$myString);
demo
You can also use T-Regx tool:
pattern('#([^#])#')->replace($input)->all()->by()->map([
'#Dear#' => "newString1",
'#an example string#' => 'newString2'
]);
or
pattern('#([^#])#')->replace($input)->all()->group(1)->by()->map([
'Dear' => "newString1",
'an example string' => 'newString2'
]);
You can also use methods by()->map(), by()->mapIfExists() or by()->mapDefault(). Whatever you need :)
i have a string, like this:
'<indirizzo>Via Universit\E0 4</indirizzo>'
Whit HEX char... i need string become:
'<indirizzo>Via Università 4</indirizzo>'
So, i use:
$text= preg_replace('/(\\\\)([a-f0-9]{2})/imu', chr(hexdec("$2")), $text);
But dont work because hexdec dont use value of $2 (that is 'E0'), but use only value '2'.
So hexdex("2") is "2" and chr("2") isnt "à"
What can i do?
$text='<indirizzo>Via Universit\E0 4</indirizzo>';
function cb($match) {
return html_entity_decode('&#'.hexdec($match[1]).';');
}
$text= preg_replace_callback('/\\\\([a-f0-9]{2})/imu', 'cb', $text);
echo $text;
You need to specify your chr(hexdec()) as a callback. Just calling those functions and suppling the result as parameter to preg_replace doesn't do it.
preg_replace_callback('/\\\([a-f0-9]{2})/imu',
function ($match) { return chr(hexdec($match[1])); },
$text)
Having said that, there are probably better ways to do what you want to do overall.
You could also use
<?php
$str = preg_replace('/\\([a-f0-9]{2})/imue', '"\x$1"', '<indirizzo>Via Universit\E0 4</indirizzo>');
I have a string like that:
[0-9A-Za-z\+/=]*
How can I converted in the following form:
"\133\x30\55\x39\101\x2d\132\x61\55\x7a\134\x2b\57\x3d\135\x2a"
Is there any function for that ?
function strtohex($string)
{
$string = str_split($string);
foreach($string as &$char)
$char = "\x".dechex(ord($char));
return implode('',$string);
}
print strtohex("[0-9A-Za-z\+/=]*");
The above code will give you
\x5b\x30\x2d\x39\x41\x2d\x5a\x61\x2d\x7a\x5c\x2b\x2f\x3d\x5d\x2a
I'm aware that it doesn't look like the output you expect, but that doesn't seem to be string to hex at all.
If you want to perform such a string obfuscation, then use something like #Kristians approach. And you can alternate between the two encoding methods with e.g.:
$char = (++$i%2) ? "\x".dechex(ord($char)) : "\\".decoct(ord($char));
How do i encode all chars in a string.
Example :
A = %32 // Or something like that
B = %33
I want to do this without hardcoding every char. And i also want to be able to decode it again.
Is there a php function for this?
Thanks.
If you really want to do this, you could do it with preg_replace_callback quite easily:
echo preg_replace_callback('/./', function($char) {
return '%' . ord($char[0]);
}, 'this is probably an unnecessary step');
// %116%104%105%115%32%105%115%32%112%114%111%98%97%98%108%121%32%97%110%32%117%110%110%101%99%101%115%115%97%114%121%32%115%116%101%112
You could reverse it with the inverse, using chr:
echo preg_replace_callback('/%[^%]*/', function($seq) {
return chr(substr($seq[0], 1));
}, '%116%104%105%115');
// this
However, this is almost certainly unnecessary for whatever you're doing...
See:
chr
ord
preg_replace_callback
try with:
urlencode($string);
urldecode($string);
http://php.net/manual/en/function.urlencode.php
http://php.net/manual/en/function.urldecode.php
Don't you just mean ord() and chr() ?
How do I remove a certain variable from a query string? Say I have a query string
$query_string = "first=val1&second=val2&third=val3";
function removevar($var, $query_string) {
return preg_replace("/(".$var."=[^&]*(&))/i","",$query_string);
}
echo removevar("first",$query_string); // ok
echo removevar("second",$query_string); // ok
echo removevar("third",$query_string); // doesn't change the string because third doesn't have a trailing &
How can this be fixed so that it removes variables from a query string in a robust way? Probably someone already has a function that does this along with special cases in more complex strings.
So I'd have to match either & or end of the string ($) but I don't know how to turn that into regex.
$query_string = "first=val1&second=val2&third=val3";
function removevar($var, $query_string) {
return preg_replace("/(".$var."=[^&]*(&|$))/i","",$query_string);
}
echo removevar("first",$query_string); // ok
echo removevar("second",$query_string); // ok
echo removevar("third",$query_string); // ok
This should do the trick.
You don’t necessarily need regular expressions for this as PHP does have functions that can parse and build query strings (parse_str and http_build_query respectively):
function removevar($var, $query_string) {
parse_str($query_string, $args);
unset($args[$var]);
return http_build_query($args);
}
Note that you need to decode the HTML character references before using these functions.
You will probably have more luck using:
html_entity_decode to get the 'normal' query-string.
parse_str to get the query string into an array.
unset the desired key in that array.
Use http_build_query to rebuild the string.
Call htmlspecialchars on it to get the & back to &.
Less concise than the regex route, but a lot less error-prone.
<?php
$query_string = "first=val1&second=val2&third=val3";
parse_str($query_string, $output);
function removevar($var, $output_array) {
if (in_array($var, $output_array)) {
unset($output_array[$var]);
}
return http_build_query($output_array, '', '&');
}
echo removevar("first", $output);
echo removevar("third", $output);
?>
Normally for codes like this, which involves a query string, it is always best to go for the in-built PHP functions rather than for the regex syntax / formula. That is what I've done, and the main parts of the code include the following PHP in-built functions:-
parse_str Function
in_array Function
http_build_query Function
Hope it helps.
function removevar($var, $query_string) {
$query_string = preg_replace("#$var=([^&]+)#is", "", $query_string);
return trim($query_string, "&");
}
There are functions, that can handle query strings directly.
function removevar ($var, $query_string) {
$array = array();
parse_str(html_entity_decode($query_string), $array);
unset($array[$var]);
return html_entities(http_build_query($array);
}