Page 1 of 1

Need regex

Posted: Fri Apr 09, 2010 5:57 am
by klevis miho
I need to get from this string:
//"dict":[{"pos":"noun","terms":["word1","word2","word3","word(n)"]}],"src":"fr"}

just the words(word1, word2 etc).

Any advice would be helpful

Re: Need regex

Posted: Tue May 25, 2010 11:40 am
by Jonah Bron
If that string is constant, this should work:

Code: Select all

$str = '//"dict":[{"pos":"noun","terms":["antidisestablishmentarianism","zygote","aardvark","wuzzup","malamanteau"]}],"src":"fr"}';
$str = substr($str, 34);
$str = substr($str, 0, strpos($str, '"]}]'));
$str = explode('","', $str);
Which can be simplified to

Code: Select all

$str = '//"dict":[{"pos":"noun","terms":["antidisestablishmentarianism","zygote","aardvark","wuzzup","malamanteau"]}],"src":"fr"}';
$str = explode('","', substr($str, 34, strpos($str, '"]}]')-34));

Re: Need regex

Posted: Tue May 25, 2010 11:47 am
by Jonah Bron
And this will make the result very easy to handle

Code: Select all

$str['pos'] = $str[0];
$str['noun'] = $str[1];
$str['terms'] = array_slice($str, 3);
unset($str[0], $str[0]);

Re: Need regex

Posted: Tue May 25, 2010 12:18 pm
by AbraCadaver
klevis miho wrote:I need to get from this string:
//"dict":[{"pos":"noun","terms":["word1","word2","word3","word(n)"]}],"src":"fr"}

just the words(word1, word2 etc).

Any advice would be helpful
This looks almost like a json string, so why not use it as such?

Code: Select all

$string = '//"dict":[{"pos":"noun","terms":["word1","word2","word3","word(n)"]}],"src":"fr"}';
$string = str_replace('//', '{', $string);
$string = json_decode($string, true);
print_r($string);
[text]Array
(
[dict] => Array
(
[0] => Array
(
[pos] => noun
[terms] => Array
(
[0] => word1
[1] => word2
[2] => word3
[3] => word(n)
)

)

)

[src] => fr
)[/text]

Code: Select all

$terms = implode(',', $string['dict'][0]['terms']);
print_r($terms);
[text]word1,word2,word3,word(n)[/text]

Re: Need regex

Posted: Tue May 25, 2010 12:52 pm
by Jonah Bron
:mrgreen: