Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/146814-solved-ereg-question/
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/146814-solved-ereg-question/#findComment-770780
Share on other sites

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).

Link to comment
https://forums.phpfreaks.com/topic/146814-solved-ereg-question/#findComment-770793
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.