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"; Link to comment https://forums.phpfreaks.com/topic/163972-solved-return-part-of-a-string/ 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!"; } ?> Link to comment https://forums.phpfreaks.com/topic/163972-solved-return-part-of-a-string/#findComment-865032 Share on other sites More sharing options...
n8w Posted June 28, 2009 Author Share Posted June 28, 2009 this is so great! thanks Link to comment https://forums.phpfreaks.com/topic/163972-solved-return-part-of-a-string/#findComment-865040 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. Link to comment https://forums.phpfreaks.com/topic/163972-solved-return-part-of-a-string/#findComment-865042 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.