如何用preg_match获取字符串的结尾?

时间:2011-12-11 22:43:24

标签: php string preg-match

我收到了这个字符串:

from:100000238267321=to:100000238267322=somethingelse: hey james, heard the news, mike is returning tomorrow!

这个preg_match命令:

#(?P<from>(?:\w|\s)+):(?P<idfrom>\d+)=(?P<to>(?:\w|\s)+):(?P<toid>\d+)=(?P<somethingelse>(?:\w|\s)+):(?P<somethingelsetxt>(?:\w|\s)+)#

我需要在'somethingelse:'之后获得所有文字。使用上面的preg_match,它只会在'hey james'之后的逗号之前。返回:

[0] from:100000238267321=to:100000238267322=somethingelse:hey james
[from]  from
[1] from
[idfrom]    100000238267321
[2] 100000238267321
[to]    to
[3] to
[toid]  100000238267322
[4] 100000238267322
[somethingelse] somethingelse
[5] somethingelse
[somethingelsetxt]  hey james
[6] hey james

我能做什么?

2 个答案:

答案 0 :(得分:3)

使用.*$获取从当前点到字符串结尾的所有内容。确保multiline修饰符已设置为.与换行符匹配,除非您确定不会有任何换行符。

答案 1 :(得分:1)

您可以使用explode获取最后一个数组值:

$string = 'from:100000238267321=to:100000238267322=somethingelse: hey james, heard the news, mike is returning tomorrow!';
$value = explode(':',$string);
echo $value[3];

请参阅codepad

更新

要解决正则表达式问题,请在somethingelsetxt正则表达式中添加“|,”,如下所示:

(?P<somethingelsetxt>(?:\w|\s|,)

这也会得到逗号。你可以包括一个“|!”如果你想要的话。