Need regex

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Need regex

Post 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
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Need regex

Post 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));
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Need regex

Post 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]);
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Need regex

Post 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]
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Need regex

Post by Jonah Bron »

:mrgreen:
Post Reply