0

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

要使用的示例字符串:

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

和所需的子字符串

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

2 回答 2

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 
于 2013-04-30T18:11:19.247 回答
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.
?>
于 2013-04-30T18:02:59.317 回答