views:

114

answers:

4

Hi

I want to convert octal sign like \46 to normal sign like &.
The problem is that the input is created with preg_match_all(), put into an array and then retrieved.

If I'd manually input the \46 octal notation into variable with double quotes, like
$input="\046";
then PHP would convert it nicely.

But when I have it into an array from preg_match_all(), it returns it unconverted.

I want to convert it because I want to query database (mysql) that have records with "&" sign as ampersand.

+1  A: 

Not particularly elegant, but you can eval the string. Of course, this will eval anything else in the string too, but maybe that is what you want. If you want to avoid evaling variables you should replace $ with \$ first.

<?php

// The string
$a='test a \046 b';

// Output "test a \046 b"
echo "$a\n";

// Convert \046 to &
eval("\$c=\"$a\";");

// Output "test a & b"
echo "$c\n";

?>
Tom
A: 

but when i have it in array from preg match all, it return it unconverted.

Try:

$tmp=implode('', $array_from_pregmatch);
$input="$tmp";
Pete
+2  A: 

there's an interesting replace trick (or rather hack)

$a = 'a \046 b \075 c';
echo preg_replace('~\\\\(0\d\d)~e', '"\\\\$1"', $a);
stereofrog
+2  A: 

Use stripcslashes()

From the stripcslashes documentation:

string stripcslashes ( string $str )
Returns a string with backslashes stripped off.
Recognizes C-like \n, \r ..., octal and hexadecimal representation.

<?php
$a = 'a \046 b \075 c';
$b = stripcslashes($a);
echo "$a ==> $b";
?>

outputs: a \046 b \075 c ==> a & b = c
Carlos Lima