20

I'd like to return string between two characters, @ and dot (.).

I tried to use regex but cannot find it working.

(@(.*?).)

Anybody?

Johannes
  • 599
  • 2
  • 5
  • 14

4 Answers4

38

Your regular expression almost works, you just forgot to escape the period. Also, in PHP you need delimiters:

'/@(.*?)\./s'

The s is the DOTALL modifier.

Here's a complete example of how you could use it in PHP:

$s = 'foo@bar.baz';
$matches = array();
$t = preg_match('/@(.*?)\./s', $s, $matches);
print_r($matches[1]);

Output:

bar
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Sorry, I didn't notice that he was using multiline strings. Updated answer. – Mark Byers Jan 09 '10 at 19:53
  • andreas didn't say he was working with strings with line breaks, I just mentioned that if he were, the proposed solution wouldn't work. And now it does, of course. – Bart Kiers Jan 09 '10 at 19:56
  • Ah, yes I see now. I'm wondering if he is trying to parse emails... just a guess though. – Mark Byers Jan 09 '10 at 20:09
  • I try to get email address domain. @Mark Byers, your example shoots me with "Unknown modifier @". When adding \ before @ got blank page. Damn, hate regex :-) – Johannes Jan 09 '10 at 20:33
  • Nevermind, I think I'm to tired :( Thanks Mark, your answer does the trick. Thanks! – Johannes Jan 09 '10 at 20:37
  • andreas, how will you know on which DOT to split? What if the address is `name@some.domain.com` or `name@some.domain.co.uk`? – Bart Kiers Jan 09 '10 at 20:47
  • 1
    Also @ is a valid character in the first part of the address as long as it is escaped or in quotes, e.g. "firstname@lastname"@example.com - see http://www.apps.ietf.org/rfc/rfc3696.html page 6. You should consider using a standards compliant email parser rather than trying to roll your own. – Mark Byers Jan 09 '10 at 20:51
  • @MarkByers what is the /s used for? it is working with just an '/' as an ending delimiter. – Aris Jul 04 '16 at 06:27
11

Try this regular expression:

@([^.]*)\.

The expression [^.]* will match any number of any character other than the dot. And the plain dot needs to be escaped as it’s a special character.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
4

this is the best and fast to use

function get_string_between ($str,$from,$to) {

    $string = substr($str, strpos($str, $from) + strlen($from));

    if (strstr ($string,$to,TRUE) != FALSE) {

        $string = strstr ($string,$to,TRUE);

    }

    return $string;

}
Yada
  • 30,349
  • 24
  • 103
  • 144
Dièse
  • 41
  • 2
3

If you're learning regex, you may want to analyse those too:

@\K[^.]++(?=\.)

(?<=@)[^.]++(?=\.)

Both these regular expressions use possessive quantifiers (++). Use them whenever you can, to prevent needless backtracking. Also, by using lookaround constructions (or \K), we can match the part between the @ and the . in $matches[0].

Geert
  • 1,804
  • 15
  • 15