PHP explode/split with 2 different delimiters

风流意气都作罢 提交于 2020-01-06 06:53:29

问题


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?

Example strings to work with:

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

and the desired substring

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

回答1:


You can do it like this:

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

or in a more explicit way

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

explanation:

first pattern:

~ : 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

second pattern:

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 



回答2:


There is probably a better way, but since I avoid regular expression like bad tennis player avoids their backhand...

<?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.
?>


来源:https://stackoverflow.com/questions/16306112/php-explode-split-with-2-different-delimiters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!