【问题标题】:PHP explode/split with 2 different delimitersPHP 使用 2 个不同的分隔符分解/拆分
【发布时间】:2013-04-30 17:58:01
【问题描述】:

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

使用的示例字符串:

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

和所需的子字符串

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

【问题讨论】:

  • 使用preg_split(): $sub = preg_split(',|:', $str); 可以使用2 个分隔符进行爆炸,但所需的输出对我来说没有意义。你能解释一下它背后的逻辑吗?
  • 数据是来自 Wordpress 数据库的复杂数组。我需要提取其中的一部分,编辑数据并用新数据更新数据库。我能想到的唯一方法是拆分字符串,编辑“中间”部分并将其重新组合在一起。
  • 所以分隔符是:,你想通过::“停止”并获得xxx:yyy::值?

标签: php string split explode


【解决方案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 

【讨论】:

  • 我在正则表达式方面很糟糕。这就是我得到的:Warning: preg_match() [function.preg-match]: No ending delimiter '~' found
  • @bikey77:我忘记了结局~。哎呀
  • 谢谢,它适用于分隔符为 :: 的示例,不适用于我也需要的 }}。你能告诉我如何相应地更改正则表达式吗?
  • @bikey77: 用 \}\} 替换 :: 因为花括号是正则表达式模式中的特殊字符
  • 也许你可以解释一下你写的正则表达式,我可以做测试?这对双方来说都会更容易更好。
【解决方案2】:

可能有更好的方法,但是由于我避免使用正则表达式,例如糟糕的网球运动员会避免反手...

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

【讨论】:

  • 我已经编辑了我的示例字符串,以明确在 abc 之前不会总是有 ::。
  • 会一直以“abc”开头吗?
  • 我编辑了我的答案,但与此同时,Casimir 可能已经以“正确”的方式解决了它。您可能需要在其中进行一些测试以确保双冒号确实存在。
猜你喜欢
  • 2014-09-29
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 2013-10-12
相关资源
最近更新 更多