extract various texts from a string variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
markjohnson
Forum Newbie
Posts: 15
Joined: Sat Feb 07, 2009 8:36 pm

extract various texts from a string variable

Post by markjohnson »

Ok, so here it goes:

I have a variable:

$var = ":12:3{this is a test}:5:8{this is another test}:"

Everything between : : is a separate value, which I can easily extract in an array:

$value=explode(":",$var);

I then get:

$value[0]=12
$value[1]=3{this is a test}
$value[2]=5
$value[3]=8{this is another test}

RE values like $value[1] and $value[3] with brackets, I would like to extract the number before the bracket '{' in one variable, and then all the text between the brackets {} in another variable, which should result in something like this:

$key=3
$keytext=this is a test

How can I achieve this?

I am sure this one will be dead simple for PHP experts, so many thanks in advance!
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: extract various texts from a string variable

Post by Benjamin »

What is the format of that string? Where is it coming from? Is it JSON?

http://us2.php.net/manual/en/function.json-decode.php
markjohnson
Forum Newbie
Posts: 15
Joined: Sat Feb 07, 2009 8:36 pm

Re: extract various texts from a string variable

Post by markjohnson »

It's a very simple string variable.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: extract various texts from a string variable

Post by Benjamin »

What created it?
markjohnson
Forum Newbie
Posts: 15
Joined: Sat Feb 07, 2009 8:36 pm

Re: extract various texts from a string variable

Post by markjohnson »

I did...

It was just a simple variable:

$var = "3{this is my var}"

Anyway, here is the solution for it:

Code: Select all

$string = '3{this is a test}';
preg_match('#^(\d+){([^}]+)}$#', $string, $matches);
list(, $key, $keytext) = $matches;
Post Reply