Jump to content

selecting part of a string


jeff5656

Recommended Posts

If I have this string:  tester123@somplace.com

 

How do I do it so that I can echo out: tester123

If the string is consistently the same format, you can just explode it and take the first element.

Link to comment
Share on other sites

Pick any one from this incomplete list:

list($username) = explode("@", $string);

$parts = explode("@", $string);
$username = $parts[0];

$username = strtok("@", $string);

$at = strpos($string, "@");
$username = substr($string, 0, $at);

preg_match('/[^@]+(?=@)/', $string, $matches);
$username = $matches[0];

$username = preg_replace('/@.*/', "", $string);

list($username) = sscanf($string, "%[^@]");

$len = strcspn($string, "@");
$username = substr($string, 0, $len);

$username = strstr($string, "@", true);

I'm partial to #3.

Link to comment
Share on other sites

I ended up using substr and strpos

Mind posting the solution so others can reference?

But you didn't post your solution for "explode" so others can reference it! :-):-)

Anyway mine was :

$user = substr($email, 0, strpos($email, "@"));

I didn't realize there were so many ways to skin this cat...Good future reference

Link to comment
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.