Convert python code to php

Question:

I found solution of my task on python. But I do not know python at all. Code:

import re
import json
a = open('test.txt').read()
a = re.sub('"[ t]*"', '":"', a)
a = re.sub('"s+"', '","', a)
a = re.sub('"s+{', '":{', a)
a = re.sub('}s+"', '},"', a)
a = '{%s}' % a
b = json.loads(a) 

Tried to convert it to php by analogy:

$a = file_get_contents('test.txt');
$a = preg_replace('"[ t]*"', '":"', $a);
$a = preg_replace('"s+"', '","', $a);
$a = preg_replace('"s+{', '":{', $a);
$a = preg_replace('}s+"', '},"', $a);
$a = '{'.$a.'}';
$b = json_decode($a);

But seems like expressions are wrong. Can someone help with it?

Asked By: Dmitriy Zhura

||

Answers:

In PHP I think regular expressions need to be inside 2 x / e.g.

$a = preg_replace('/"[ t]*"/', '":"', $a);

Edit: As AndrĂ© mentioned, the delimiter does not necessarily need to be forward slashes, however I think the double quotes you’re using are meant to be used as part of the regular expression rather than the delimiters.

Answered By: Jonathon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.