markjohnson Posted March 15, 2009 Share Posted March 15, 2009 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! Quote Link to comment https://forums.phpfreaks.com/topic/149554-solved-extract-various-texts-from-a-variable/ Share on other sites More sharing options...
Daniel0 Posted March 15, 2009 Share Posted March 15, 2009 You can use regular expressions: $string = '3{this is a test}'; preg_match('#^(\d+){([^}]+)}$#', $string, $matches)); list(, $key, $keytext) = $matches; Quote Link to comment https://forums.phpfreaks.com/topic/149554-solved-extract-various-texts-from-a-variable/#findComment-785366 Share on other sites More sharing options...
markjohnson Posted March 15, 2009 Author Share Posted March 15, 2009 Thanks, mate. But this line: preg_match('#^(\d+){([^}]+)}$#', $string, $matches)); gives parsing error. Quote Link to comment https://forums.phpfreaks.com/topic/149554-solved-extract-various-texts-from-a-variable/#findComment-785413 Share on other sites More sharing options...
Daniel0 Posted March 15, 2009 Share Posted March 15, 2009 Oh sorry, an extra closing parenthesis slipped in. Just remove it, i.e. preg_match('#^(\d+){([^}]+)}$#', $string, $matches); Quote Link to comment https://forums.phpfreaks.com/topic/149554-solved-extract-various-texts-from-a-variable/#findComment-785422 Share on other sites More sharing options...
markjohnson Posted March 15, 2009 Author Share Posted March 15, 2009 Cheers, mate! Worked like a charm! Quote Link to comment https://forums.phpfreaks.com/topic/149554-solved-extract-various-texts-from-a-variable/#findComment-785447 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.