Forum Moderators: coopster

Message Too Old, No Replies

Trouble translating characters

         

timster

12:15 am on Jul 18, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to write some PHP code that will do what either of these 2 lines of Perl code will do (that is change square brackets to carets):

s~([\[\]])~ chr(ord($1)-31)~ge; 
y~\[\]~<>~;

Attempts such as this line haven't worked:

$text2 = preg_replace($pattern, chr(ord("\\1")-31), $text);

Advice?

dklynn

4:19 am on Jul 18, 2004 (gmt 0)

10+ Year Member



I would try:

<?php

$patterns[0] = "[";
$patterns[1] = "]";
$replacement[0] = "<";
$replacement[1] = ">";

$text2 = preg_replace($patterns, $replacements, $text);

?>

Regards,

DK

timster

1:00 pm on Jul 18, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the tip. I had to tweak the code just a little; here's how it looks:

$patterns[0] = '/\[/';
$patterns[1] = '/\]/';
$replacements[0] = '<';
$replacements[1] = '>';

$text2 = preg_replace($patterns, $replacements, $text);

I'm still interested whether

ord
and backreferences can play nicely together.

ergophobe

4:04 pm on Jul 18, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




I'm still interested whether ord and backreferences can play nicely together.

That would be surprising, wouldn't it? In other words, the "replace" expression is first evaluated, then sent to the regex engine. You're asking it to do the opposite. So in your case,

ord("\\1") evaluates to ASCII value of the first character of the string "\1" which evaluates to 92. chr(92-31) evaluates to "="

so this expression


$text2 = preg_replace($pattern, chr(ord("\\1")-31), $text);

is the same as


$text2 = preg_replace($pattern, "=", $text);

So it should be changing all your brackets to "=".

timster

12:40 pm on Jul 20, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, I'm still hoping I'll be able to do everything in PHP that I've done in Perl. If I might bring up one more example, consider the following handsome line of code:

s/([^\w\s])/ sprintf('\0%o;', ord($1)) /ge;

This translates a whole slew of characters (anything that's not a word or whitespace character) into an octal escape sequence. Is there a way to do this in PHP?

I'm not trying to start a "language death match" here -- just coming up to speed with PHP.