3

Original regexp:

$str = '"foo" <[email protected]>';
preg_replace('/\s(<.*?>)|"/', '', $str);

I would like to extract the following:

"foo" <[email protected]> extract only => foo
<[email protected]>       extract only => <[email protected]>
"" <[email protected]>    extract only => <[email protected]>

Thanks

1
  • can you clarify what you are actually trying to do here? because if you are trying to get the value, preg_replace() isn't really the right function for that... Commented May 4, 2011 at 14:08

2 Answers 2

3

Okay, so it looks like you are wanting to get a value, rather than replace a value, so you should be using preg_match, not preg_replace (though technically you could use preg_replace in a round-about way...)

preg_match('~(?:"([^"]*)")?\s*(.*)~',$str,$match);
$var = ($match[1])? $match[1] : $match[2];
Sign up to request clarification or add additional context in comments.

Comments

0

You need to require something inside the quotes when you do the replace.

$str = '"foo" <[email protected]>';
preg_replace('/"([^"]+)"\s(<.*?>)/', '$1', $str);
preg_replace('/""\s(<.*?>)/', '$1', $str);

Try that. It should leave the address alone if there's no quoted name before it.

Edit: Based on your new example inputs and outputs, try this:

$str = '"foo" <[email protected]>';
preg_replace('/"([^"]+)"\s(<.*?>)/', '$1', $str);
preg_replace('/(?:""\s)?(<.*?>)/', '$1', $str);

It should have the following input/output results:

"foo" <[email protected]>  -> foo
"" <[email protected]>     -> <[email protected]>
<[email protected]>        -> <[email protected]>

5 Comments

is there a way to extract the name only if between quotes, and not both?
@Mike - Not sure I understand. Could you explain what you mean by that? The above code should turn "foo" <[email protected]> into foo, and "" <[email protected]> into <[email protected]>.
you should be using preg_match instead of preg_replace...I mean yah it "works" but that's not really what preg_replace was designed for..
@Crayon - Depends on what he's trying to do. I could go either way with it, especially since preg_replace works without too much difficulty. If you want a one-liner, it's a job for preg_match or preg_replace_callback. Many roads to the same place. :)
@Mike: Yes, like I said, it "works". But why take the long and winding path over the straight?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.