【问题标题】:php explode between two delimiter and delimiter not lostphp在两个分隔符之间爆炸并且分隔符不丢失
【发布时间】:2020-12-13 16:08:37
【问题描述】:

如何在分隔符“[”之间分解字符串,但我希望分隔符不会丢失 例如我有这样的字符串

$str = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]

我想要这样的结果

  [0]=>
  string(61) "i want to show you my youtube channel : [youtube id=12341234]"
  [1]=>
  string(68) "and my instagram account : [instagram id=myingaccount213]"

如果我使用$tes = explode("]", $content);,“]”会丢失

【问题讨论】:

  • 有什么特殊原因不能使用不同的分隔符吗?例如:$str =“我想向您展示我的 youtube 频道:[youtube id=12341234] | 和我的 Instagram 帐户:[instagram id=myingaccount213]”。
  • @AbsoluteBeginner 我认为特别的原因是字符串中的 BBCode(公告板代码)

标签: php regex explode


【解决方案1】:

除了拆分之外,您还可以通过匹配可选的水平空白字符来匹配所需的部分,然后在第 1 组中捕获尽可能少的字符,然后匹配 [...]

对于匹配项,使用 $matches[1] 获取第 1 组值

\h*(.*?\[[^][]*])

Regex demo | Php demo

示例代码

$s = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]";
preg_match_all("~\h*(.*?\[[^][]*])~", $s, $matches);
print_r($matches[1]);

输出

Array
(
    [0] => i want to show you my youtube channel : [youtube id=12341234]
    [1] => and my instagram account : [instagram id=myingaccount213]
)

另一种选择是让模式更适合 youtube 或 instagram:

\h*(.*?\[(?:youtube|instagram)\h+id=[^][\s]+])

Regex demo

【讨论】:

    【解决方案2】:

    如果字符串只包含一个

    $newStr = substr($str, strpos($str, '[') -1, strlen($str) - strpos($str, ']');
    

    preg_match('/\[.+\]/', $str, $matches, PREG_OFFSET_CAPTURE);
    

    【讨论】:

      【解决方案3】:

      请尝试:

      $str = explode('|', str_replace('] ', ']|', $str));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多