field
field

Reputation: 45

convert ASCII value to a character based on specific char in php

I'd like to ask dumb question. How could I convert @48@49@50 based on @ char ? In PHP, understand that chr() function is used to convert a ASCII value to a character. 48 is 0. 49 is 1. And 50 is 2. May I know how to convert @48@49@50 as 012 and how to store 012 in one variable ? Eg- $num = 012

Upvotes: 1

Views: 207

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

We can try using preg_replace_callback() here with the regex pattern @\d+. As we capture each @\d+ match, use chr() on that match to generate the ASCII character replacement.

$input = "@48@49@50";
$out = preg_replace_callback(
    "/@(\d+)/",
    function($m) { return chr($m[1]); },
    $input
);

echo $out;  // 012

Upvotes: 1

Related Questions