PHP string to hex - php

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

Related

php replace some strings between tags or chars

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

Trim a string until specific character appears

I want to trim a string and delete everything before a specific character, because I am using an API that gives me some unwanted data in its callback which I want to delete.
The Callback looks like this:
{"someVar":true,"anotherVar":false,"items":[ {"id":123456, [...] }
And I only want the code after the [ , so how can I split a string like this?
Thank you!
It is JSON, so you could just decode it:
$data = json_decode($string);
If you really want to trim up to a certain character then you can just find the character's position and then cut off everything before it:
if (($i = strpos($string, '[')) !== false) {
$string = substr($string, $i + 1);
}
You can use various functions. For example:
$someVar = explode('[',$string,2);
$wantedData = $someVar[1];
Or if you want only data between [ and ] then use:
$pattern = '~\[([^\]])\]~Ui';
if (preg_match($pattern,$inputString,$matches) {
$wantedData = $matches[1];
}
Edit:
Thats what you use if you want extract some string from another. But as #Dagon noticed, it's json and you can use other function to parse it. I will leave above anyway, because it's more general to the question of extracting string from another.

What is this encoding and how can I encode a string to it in PHP?

I have an input like this:
$input = 'GFL/R&D/50/67289';
I am trying to get to this:
GFL$2fR$26D$2f50$2f67289
So far, the closest I have come is this:
echo filter_var($input, FILTER_SANITIZE_ENCODED, FILTER_FLAG_ENCODE_LOW)
which produces:
GFL%2FR%26D%2F50%2F67289
How can I get from the given input to the desired output and what sort of encoding is the result in?
By the way, please note the case sensitivity going on there. $2f is required rather than $2F.
This will do the trick: url-encode, then lower-case the encoded sequences and swap % for $ with a preg callback (PHP's PCRE doesn't support case-shifting modifiers):
$input = 'GFL/R&D/50/67289';
echo preg_replace_callback('/(%)([0-9A-F]{2})/', function ($m) {
return '$' . strtolower($m[2]);
}, urlencode($input));
output:
GFL$2fR$26D$2f50$2f67289

PHP equivalent for javascript escape/unescape

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

Replace characters with word in PHP?

Want to replace specific letters in a string to a full word.
I'm using:
function spec2hex($instr) {
for ($i=0; $i<strlen($instr); $i++) {
$char = substr($instr, $i,1);
if ($char == "a"){
$char = "hello";
}
$convString .= "&#".ord($char).";";
}
return $convString;
}
$myString = "adam";
$convertedString = spec2hex($myString);
echo $convertedString;
but that's returning:
hdhm
How do I do this? By the way, this is to replace punctuation with hex characters.
Thanks all.
Use http://php.net/substr_replace
substr_replace($instr, $word, $i,1);
ord() expects only a SINGLE character. You're passing in hello, so ord is doing its thing only on the h:
php > echo ord('hello');
104
php > echo ord('h');
104
So in effect your output is actually
hdhm
it you want to use your same code just change $convString .= "&#".ord($char).";";
to $convString .= $char;
If you just want to replace the occurrence of a with hello within the string you pass to the function, why not use PHP's str_replace()?
function spec2hex($instr) {
return str_replace("a","hello",$instr);
}
I must assume that you don't want to have hex characters instead of punctuation but html entities. Be aware that str_replace(), when called with arrays, will run over the string for multiple times, thus replacing the ";" in "{" also!
Your posted code is not useful for replacing punctuation.
use strtr() with arrays, it doesn't have the drawback of str_replace().
$aReplacements = array(',' => ',', '.' => '.'); //todo: complete the array
$sText = strtr($sText, $aReplacements);

Categories