Search code examples
phpregextext-extraction

Get substring between two substrings


I have a string and I want to extract out some information for it. The string could be like this

$string = "Followers: abc.com. ID by: [email protected]. More info: all the rest of information goes here. All other goes everywhere else."

the $string sometimes just have

$string = "ID by: [email protected]."

or

$string = "Followers: abc.com."

or any other combo. I am just trying to see if there is ID by there and get that out.

What would be the best way to achieve this?


Solution

  • Use a regular expression with preg_match to find the ID.

    preg_match('/ID by\\: ([\\w@\\.]+)\\.(?: |$)/',$input,$matches);
    

    The ID (email address) will be in $matches[1]. The pattern matches "ID by: ", captures the email address, and finally requires a period + space or end of string.