PHP使用2个不同的分隔符进行爆炸/拆分

时间:2013-04-30 17:58:02

标签: php string split explode

在下面的字符串$str中我需要爆炸/拆分数据获取部分'abc'和第一次出现'::'然后将它们全部重新打包到单个字符串。爆炸可以一步完成而不是两次连续爆炸吗?

要使用的示例字符串:

$str="12345:hello abcdef123:test,demo::example::12345";

和所需的子字符串

$substr = "abcdef123:test,demo::"

2 个答案:

答案 0 :(得分:1)

你可以这样做:

preg_match('~\s\Kabc\S+?::~', $str , $match);
$result = $match[0];

或以更明确的方式

preg_match('~\s\Kabc\w*+:\w++(?>,\w++)*+::~', $str , $match);
$result = $match[0];

说明:

第一种模式:

~ : delimiter of the pattern
\s : any space or tab or newline (something blank)
\K : forget all that you have matched before
abc : your prefix
\S+? : all chars that are not in \s one or more time (+) without greed (?) 
     : (must not eat the :: after)
~ : ending delimiter

第二种模式:

begin like the first
\w*+ : any chars in [a-zA-Z0-9] zero or more time with greed (*) and the 
     : RE engine don't backtrack when fail (+) 
     : (make the previous quantifier * "possessive")
":"  : like in the string
\w++ : same as previous but one or more time
(?> )*+ : atomic non capturing group (no backtrack inside) zero or more time 
     : with greed and possessive *+ (no backtrack)
"::" : like in the string
~    : ending delimiter 

答案 1 :(得分:0)

可能有更好的方法,但是因为我避免像坏网球运动员这样的正常表达避免反手......

<?php
list($trash,$keep)=explode('abc',$str);
$keep='abc'.$keep;
list($substring,$trash)=explode('::',$keep);
$substring.='::'; //only if you want to force the double colon on the end.
?>