Ereg_replace with a String

71 Views Asked by At

I have a string like this:

$str = "{gfgd}i:123;a:7:{gfgd}i:5;a:35:"; 

And I want to replace it to:

$str = "{gfgd},{gfgd},"; 

I want to use ereg_replace with it and replace this kind of phrase:

"i:[0-9]a:[0-9]:" into "," sign.

I try it:

     $str = "i:143;a:5:{gfgd}i:123;a:7:{gfgd}i:5;a:35:";  
     $text = ereg_replace("/^i:[0-9]+;a:[0-9]+:+$", ",", $str);

But i doesn't work. Can you help me? Thank you in advance

3

There are 3 best solutions below

0
Sabuj Hassan On
$str = "i:143;a:5:{gfgd}i:123;a:7{gfgd}i:5;a:35";  
$str = ereg_replace("\}[^\{]+\{", "},{", $str); // replace between } and { with },{
$str = ereg_replace("^[^\{]+", "", $str); // remove from first
$str = ereg_replace("[^\}]+$", ",", $str); // remove from last 
print $str;
0
anubhava On

Don't use ereg_replace as This function has been DEPRECATED as of PHP 5.3.0

Use preg_replace instead and your regex is wrong. Remove anchors ^ and $

$text = preg_replace('/i:[0-9]+;a:[0-9]+:?/', ",", $str);
//=> ,{gfgd},{gfgd},

Online Demo: http://ideone.com/W2P55n

2
Lex Podgorny On

It looks like you are dealing with a PHP array or object serialized into string. I recommend running:

<?php
    $arrayOrObject = unserialize($theEntireStringYouGot);
    print_r($arrayOrObject);
?>

That way you may not need to even deal with regex at all.

Note: it will not unserialize a piece of string like in your example, feed it the whole thing.