n8w Posted June 28, 2009 Share Posted June 28, 2009 I want to dynamically search a string. So if $id=339; I would like it to return the number after the ":" which would be "3" What is the best way to do this? $id=339; $str="338:1, 339:3 ,340:15"; Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted June 28, 2009 Share Posted June 28, 2009 Well if you're going to need to search the same string multiple times, i'd build an array: <?php $id=339; $str="338:1, 339:3 ,340:15"; $pieces = explode(",",$str); $array = array(); foreach($pieces as $piece){ $piece = trim($piece); list($key,$value) = explode(":",$piece); $array[$key] = $value; } //can then access based on id if(isset($array[$id]){ echo $array[$id]; }else{ echo "That id doesn't exist!"; } ?> If it's just the once, a regex would be neater. Edit: e.g: <?php $id=359; $str="338:1, 339:3 ,340:15"; preg_match("|$id:([0-9]+)|",$str,$matches); if(count($matches) > 0){ echo $matches[1]; }else{ echo "That ID doesn't exist!"; } ?> Quote Link to comment Share on other sites More sharing options...
n8w Posted June 28, 2009 Author Share Posted June 28, 2009 this is so great! thanks Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted June 28, 2009 Share Posted June 28, 2009 No problem. Don't forget to mark your topic solved if you're done with it. You can find the option at the bottom left of the page -- just above the quick reply. I've done this one for you. Quote Link to comment 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.