Page 1 of 1

Replace 'h' with 'h'

Posted: Sun Mar 05, 2006 4:17 pm
by nigma
I haven't been able to figure out how to replace "h" with "h", "&x69;" with "i", etc.

Anyone want to offer some help?

Re: Replace 'h' with 'h'

Posted: Sun Mar 05, 2006 4:36 pm
by Chris Corbyn
nigma wrote:I haven't been able to figure out how to replace "h" with "h", "&x69;" with "i", etc.

Anyone want to offer some help?
Here's a hint:

Code: Select all

echo chr(0x68);
Bah I just gotta give the answer. It's a preg_replace_callback().

Code: Select all

function make_ascii($chr)
{
    $chr = $chr[1];
    if (substr($chr, 0, 1) == 'x')
    {
        $chr = '0'.$chr;
    }
    return chr($chr);
}

echo preg_replace_callback('@&#([a-z0-9]+);@is', 'make_ascii', $string);

Posted: Sun Mar 05, 2006 4:38 pm
by feyd
Are the numbers in hex or decimal? What's the acceptable limits of these numbers? Are you wanting to make it UTF-8 or just translate to ANSI?

Posted: Sun Mar 05, 2006 4:43 pm
by nigma
Characters are in hex, I want to translate to the human readable ANSI character. d11, I'm probably going to end up using this in ruby, and I don't know if ruby has a preg_replace_callback function.

Thanks for the help.

Posted: Sun Mar 05, 2006 5:29 pm
by Chris Corbyn
Assuming ruby has some PCRE regex handling, a way to evaluate basic code and a way to get substrings....

Code: Select all

<?php

$string = "&#x69; & also; x &#x68;";

preg_match_all('@(&#x[a-f0-9]+;|.)@is', $string, $matches); //Any *global* search

print_r($matches);

$str = '';

for ($i=0; $i<count($matches[1]); $i++) //All the 1st backreferences
{
        if (preg_match('/^&#x[a-f0-9]+;$/i', $matches[1][$i])) //An entity
        {
                $hex = substr($matches[1][$i], 2, -1); //Remove the syntax
                $tmp = '\\'.$hex; //Build a string
                $str .= eval("return \"$tmp\";"); //Evaluate it
        }
        else
        {
                $str .= $matches[1][$i]; //Doesn't need parsing
        }
}

echo $str;

?>

Posted: Sun Mar 05, 2006 5:44 pm
by nigma
d11wtq wrote:Assuming ruby has some PCRE regex handling, a way to evaluate basic code and a way to get substrings....
Actually, regex features of Ruby were taken from Perl, so yes :)

Thanks for the help, I'll give this a shot.