匹配前后的正则表达式分割位置

时间:2016-11-02 20:47:42

标签: php regex

我正在尝试使用包含preg_split形式的标记的PHP [fbes_keep]...[/fbes_keep]拆分字符串。

我的正则表达式是(?=\[\/?fbes_(remove|keep)])regex101 link

我的输入是

[fbes_keep]hello[/fbes_keep][fbes_remove]goodbye[/fbes_remove]

我使用的代码是$fragments = preg_split( '@(?=\[\/?fbes_(remove|keep)])@i', $original );

我想要的是分割是这样的:(其中|字符是一个分割,添加了空格以便于阅读)

[fbes_keep] | hello | [/fbes_keep] | [fbes_remove] | goodbye | [/fbes_remove]

但我得到的分裂是:

[fbes_keep]hello | [/fbes_keep] | [fbes_remove]goodbye | [/fbes_remove]

我需要改变什么?

3 个答案:

答案 0 :(得分:1)

您是否尝试过$var = explode("|", $myString);

你正试图获得"你好"和"再见"价值观,对吧?

答案 1 :(得分:1)

preg_match_allimplode函数使用以下方法:

$str = '[fbes_keep]hello[/fbes_keep][fbes_remove]goodbye[/fbes_remove]';
preg_match_all("/\[\/?[a-z_]+\]|[a-z]+\b/", $str, $matches);
$result = implode(" | ", $matches[0]);

print_r($result);

输出:

[fbes_keep] | hello | [/fbes_keep] | [fbes_remove] | goodbye | [/fbes_remove]

答案 2 :(得分:0)

使用preg_match_all并循环匹配以获得更多组织和使用结果的灵活性:

   $str = '[fbes_keep]hello[/fbes_keep][fbes_remove]goodbye[/fbes_remove]';
    preg_match_all('@([[][^]]*[]])([^[]*)([[]/[^]]*[]])@Ui', $str, $matches);

    /*
    // die('<pre>'.print_r($matches,true));
    Array
    (
        [0] => Array
            (
                [0] => [fbes_keep]hello[/fbes_keep]
                [1] => [fbes_remove]goodbye[/fbes_remove]
            )

        [1] => Array
            (
                [0] => [fbes_keep]
                [1] => [fbes_remove]
            )

        [2] => Array
            (
                [0] => hello
                [1] => goodbye
            )

        [3] => Array
            (
                [0] => [/fbes_keep]
                [1] => [/fbes_remove]
            )

    )
    */

更新1

    // how many matches you have is here
    $count_of_matches = count($matches[0]);

    // to answer your comment question...get the 3 parts for match group 0
    $match_group = 0; // you also have a match_group 1
    // loop over them if you like // foreach ($matches[0] as $match_group=>$full_match) {

    // for now, loop over the match group 0's 3 outputs
    for ($i=1; $i<4; $i++) {
      echo $matches[$i][$match_group].', ';
    }
    // [fbes_keep], hello, [/fbes_keep], 

    // or access them directly
    echo "{$matches[1][0]}, {$matches[2][0]}, {$matches[3][0]}";

更新2

    // here is the full, double loop grabbing all of them
    foreach ($matches[0] as $match_group=>$full_match) {
      for ($i=1; $i<4; $i++) {
        echo $matches[$i][$match_group].', ';
      }
      echo '<br>';
    }

    /* yielding
    [fbes_keep], hello, [/fbes_keep],
    [fbes_remove], goodbye, [/fbes_remove],
    */