PHP爆炸/拆分了2个不同的分隔符 [英] PHP explode/split with 2 different delimiters
本文介绍了PHP爆炸/拆分了2个不同的分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的字符串$str
中,我需要爆炸/分割数据以获取部分'abc'和 first 出现的'::',然后将其全部内聚在一起细绳.爆炸可以一步完成,而不是连续两次爆炸吗?
In the following string $str
I need to explode/split the data get the part 'abc' and the first occurrence of '::' and then implode it all back together to a single string. Can the explode be done in one step instead of two consecutive explodes?
要使用的示例字符串:
$str="12345:hello abcdef123:test,demo::example::12345";
和所需的子字符串
$substr = "abcdef123:test,demo::"
推荐答案
您可以这样做:
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
这篇关于PHP爆炸/拆分了2个不同的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文