将字符串分解为两个字符串

I have string:

$local->string = '@John Smith: I have: milk, cookies and wine';

And I want explode this to two string. First 'John Smith' and second 'I have: milk, cookies and wine'. I can use explode, but when I write:

explode(':', $local->string);

I get:

  1. @John Smith

  2. (space)I have

  3. (space)milk, cookies and wine

I know it's regexp way to result this, but I dont know regexp :-/

Please, help me :)

This shouldn't be too hard with a regex. Assuming your string is always @<name>: <text>, then you can try this:

/@(.*?): (.*)/

Then you can use that with preg_match():

if(preg_match('/@(.*?): (.*)/', $local->string, $match) > 0){
    // These will be your matched groups
    echo $match[1];  // the name
    echo $match[2];  // the text
}

Use the $limit parameter of the function, as you can find in the documentation:

$local->string = '@John Smith: I have: milk, cookies and wine';
$temp = explode (':', $local -> string, 2);

When you want to learn regex (which is a great idea), go to this page: http://regexone.com/. Great tutorial. But, always remember to make sure you know which tools to use at which time. In this situation, the explode(...) function is clearly enough to suit your needs.

explode(':', $local->string, 2);

just look at the docs :)

You don't need regex for that. Just search for the first position of the : character:

$local->string = '@John Smith: I have: milk, cookies and wine';
$pos = strpos($local->string, ':');

if (false !== $pos) {
    $firstPart = substr($local->string, 0, $pos);
    $secondPart = substr($local->string, $pos + 1);
}

You can pass the limit as the third parameter of explode that will do the job.

$split = explode(':', '@John Smith: I have: milk, cookies and wine', 2);
echo $split[1]; //output ' I have: milk, cookies and wine'

You just have to remove the @ and the first space, that is, remove the first character in each split

If you dont know regex keep it simple

$string = '@John Smith: I have: milk, cookies and wine';

$t = explode(':', $string, 2);

$t[0] = str_replace( '@', '', $t[0] );
$t[1] = str_replace( ':', '', $t[1] );
$t[1] = trim($t[1]);

So

Array
(
    [0] => John Smith
    [1] => I have milk, cookies and wine
)

There has already been an answer I will just offer another solution:

$string = '@John Smith: I have: milk, cookies and wine';
list($name, $items) = explode(":", $string, 2);

This will assign $name the first section, and $items the second. This can be useful if you don't want an array returned and know there will always be X results (2 in this case).