dimkasmir Posted February 25, 2009 Share Posted February 25, 2009 I am trying to use ereg to retrieve data. Say I want to find all numbers after the phrase "good" so my regex would be "good([0-9]*)". However I want ereg to only output the numerical part which I am searching for, not including the "good". How do I do this? Thank you to anyone who can help. Quote Link to comment https://forums.phpfreaks.com/topic/146814-solved-ereg-question/ Share on other sites More sharing options...
nrg_alpha Posted February 25, 2009 Share Posted February 25, 2009 I would recommend not using ereg anymore, as POSIX (which ereg is) will not be included in the core as of PHP as of version 6. Futureproof yourself now and learn to use preg instead (PCRE). So as for your situation, you can use something like: $str = 'good78'; if(preg_match('#good(\d*)#', $str, $match)){ if(isset($match[1]) && $match[1] != ''){ echo $match[1]; // output number(s) after 'good' } else { echo 'No numbers found!'; } } else { echo 'Pattern not found in string!'; } If there are numbers after good, they will be captured (the \d* within the brackets, which is stored into $match[1]) and outputted. If the string just has good with no numbers afterwards, the capture will most likely create an empty string as a value of '', thus this fails the conditions set forth. I point you to phpfreak's resources, as well their tutorial or even this one. Quote Link to comment https://forums.phpfreaks.com/topic/146814-solved-ereg-question/#findComment-770780 Share on other sites More sharing options...
dimkasmir Posted February 25, 2009 Author Share Posted February 25, 2009 Thanks for the fast reply! It works like a charm but one question: what are the '#'s do in which the regex phrase is nested for? Quote Link to comment https://forums.phpfreaks.com/topic/146814-solved-ereg-question/#findComment-770787 Share on other sites More sharing options...
nrg_alpha Posted February 25, 2009 Share Posted February 25, 2009 Thanks for the fast reply! It works like a charm but one question: what are the '#'s do in which the regex phrase is nested for? Those are called delimiters.. unlike ereg, preg needs delimiters. You can have a look at this link which is from the initial resources link I mentioned in my previous thread. Have a look at those links.. it will all make sense once you do.. (and for the record, delimiters do not have to be #... commonly, they are /....../. Delimiters can be any non alphanumeric, non whitespace character (except backslashes). Quote Link to comment https://forums.phpfreaks.com/topic/146814-solved-ereg-question/#findComment-770793 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.