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


Regex split position before and after match

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

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

输入是

[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]

我需要改变什么?

您试过$var = explode("|", $myString);吗?

你想获取" hello "answers" goodbye "的值,对吗?

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]

使用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],
    */