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

时间:2014-02-17 16:08:52

标签: php regex

我有字符串:

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

我想把它爆炸成两个字符串。第一个'约翰史密斯'和第二'我有:牛奶,饼干和葡萄酒'。我可以使用爆炸,但是当我写:

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

我明白了:

  1. @John Smith

  2. (空格)我有

  3. (空间)牛奶,饼干和葡萄酒

  4. 我知道这是结果的结果,但我不知道regexp: - /

    请帮帮我:)

7 个答案:

答案 0 :(得分:3)

使用该功能的$limit参数,您可以在documentation中找到:

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

如果您想学习正则表达式(这是一个好主意),请转到此页面:http://regexone.com/。很棒的教程。但是,请记住确保您知道在哪个时间使用哪些工具。在这种情况下,explode(...)功能显然足以满足您的需求。

答案 1 :(得分:1)

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

只看文档:)

答案 2 :(得分:1)

这对正则表达式来说不应该太难。假设你的字符串总是 @<name>: <text>,那么你可以试试这个:

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

然后您可以将其与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
}

答案 3 :(得分:1)

已经有一个答案,我将提供另一种解决方案:

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

这将为第一部分分配$name,为第二部分分配$items。如果您不想返回一个数组并且知道总会有X结果(在这种情况下为2),这可能很有用。

答案 4 :(得分:0)

你不需要正则表达式。只需搜索:字符的第一个位置:

$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);
}

答案 5 :(得分:0)

您可以将限制作为爆炸的第三个参数来传递。

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

您只需删除@和第一个空格,即删除每个分割中的第一个字符

答案 6 :(得分:0)

如果你不知道正则表达式,请保持简单

$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]);

所以

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