How to convert PHP preg_replace_callback to C#?

January 24, 2022, at 02:20 AM

I have such a code in PHP, but I need to rewrite it in C#. Suggest any options please.

$output = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $input);
Answer 1

So.. With my limited php knowledge and pure googleing, lets break this down into the following parks

1 The regex: '/\\\\u([0-9a-fA-F]{4})/'

2 What is pack('H*', $match[1])

3 What is mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');

4 what does it all mean

1 This regex looks to be looking for unicode characters (though, I would have expected a + between U and the code.. so maybe some formatting has already occurred.

2 pack() converts data into a binary string.

Based on the documentation, H is the format Hex string, high nibble first and the * is the repeater argument to say use the whole input data. Based on:

The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

and finally $match[1] is taking the first matching subgroup i.e. ([0-9a-fA-F]{4}).

3 mb_convert_encoding means to convert the encoding of the string from A to B. So putting this all together, mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); means take the match of [0-9a-fA-F]{4}, convert it to a Hex-String, then change the encoding of this Hex-String from UCS-2BE to UTF-8

4 So we've defined what the regex is, and what the callback is doing. Simply, now the preg_replace_callback is taking an input, seeing if it matches the regex (so does it contain a unicode character) and if it does apply the callback, if not, returns the input unchanged.

I need to head out, so can't write a c# equivalent right now, but enough information to get you started :). Any PHP expert please correct me where I am wrong :D

Chaincode Installation error in Hyperledger Fabric 2.2

Chaincode Installation error in Hyperledger Fabric 2.2

~/go/src/githubcom/hyperledger/fabric-samples/test-network$ peer lifecycle chaincode install simple_chaincode

RNFSManager.RNFSFileTypeRegular is undefined

RNFSManager.RNFSFileTypeRegular is undefined

Am using Expo SDK 42 and react-native : 063