PHP Preg Match,获取特定模式之间的值

PHP Preg Match, get value between specific pattern

我有一个 php 应用程序将以下输出保存在数据库中:

::cck_gx::gx::/cck_gx::
::i1|0|gx::Lorem::/i1|0|gx::
::head1|0|gx::ipsum::/head1|0|gx::
::tx1|0|gx::dolor, fithos lusec.::/tx1|0|gx::
::cckend_gx::::/cckend_gx::
::cck_gx::gx::/cck_gx::
::i1|1|gx::calendar::/i1|1|gx::
::head1|1|gx::1 Fatura Grátis Por Ano::/head1|1|gx::
::tx1|1|gx::10% de cada mensalidade é reservado, e o valor acumulado até a renovação do Seguro Porto Seguro ou Azul Seguros, é devolvido em forma de desconto. Ou seja, Cliente Conecta pode ter uma fatura de celular grátis por ano.::/tx1|1|gx::

我想使用 preg_match 从该输出中检索信息。例如,在下面的示例中检索 "Lorem" 和 "ipsum" 相同位置的任何值:

::i1|0|gx::Lorem::/i1|0|gx::
::head1|0|gx::ipsum::/head1|0|gx::

但我对 preg_match 语法一无所知。

我知道我需要为每个 "label" 进行不同的预匹配(例如 preg_match 检索所有 "i1" 值,不同的 preg_match 检索所有"head1" 等等)。我只需要一个例子来理解正确的模式。

此外,最后一行是一个包含许多不同字符的示例,例如数字、逗号、“%”等,我不确定这是否会扰乱语法。

这是我两次失败的尝试:

preg_match('~[::i1|0|gx::](.*?)[/::i1|0|gx::]~', $maindata->introtext, $match1a);
 preg_match('::i1|0|gx::(.*?)::/i1|0|gx::', $maindata->introtext, $match1a);
 preg_match('/::i1|0|gx::(.*?)::.i1|0|gx::/', $maindata->introtext, $match1a);

希望这会有所帮助

<?php
    $str = '::i1|0|gx::Lorem::/i1|0|gx::';
    preg_match('/(?<=gx::).*(?=::\/)/', $str);

您也可以使用preg_match_all()

<?php
    $str = '::cck_gx::gx::/cck_gx::
    ::i1|0|gx::Lorem::/i1|0|gx::
    ::head1|0|gx::ipsum::/head1|0|gx::
    ::tx1|0|gx::dolor, fithos lusec.::/tx1|0|gx::
    ::cckend_gx::::/cckend_gx::
    ::cck_gx::gx::/cck_gx::
    ::i1|1|gx::calendar::/i1|1|gx::
    ::head1|1|gx::1 Fatura Grátis Por Ano::/head1|1|gx::';

    preg_match_all('/(?<=gx::).*(?=::\/)/', $str, $matches);
    var_dump($matches);

(?<=gx::) 正面回顾 - 断言下面的正则表达式可以匹配

. 匹配任意字符(换行符除外)

*介于零次和无限次之间,越多越好

(?=::\/) Positive Lookahead - 断言下面的正则表达式可以匹配

:: 匹配字符 :: literally

\/匹配字符/字面意思

您可以想出以下正则表达式:

::(\w+)[^::]+::(?<content>.*?)::(?=\/)

一个PHP代码片段和自由空间模式下正则表达式的解释如下所示。看到一个 example for it on regex101.

<?php
$string = '
::cck_gx::gx::/cck_gx::
::i1|0|gx::Lorem::/i1|0|gx::
::head1|0|gx::ipsum::/head1|0|gx::
::tx1|0|gx::dolor, fithos lusec.::/tx1|0|gx::
::cckend_gx::::/cckend_gx::
::cck_gx::gx::/cck_gx::
::i1|1|gx::calendar::/i1|1|gx::
::head1|1|gx::1 Fatura Grátis Por Ano::/head1|1|gx::
';

$regex = '~
        ::
        (\w+)
        # tag 
        [^:]+::
        # match everything except a colon, then two colons 
        (?<content>.*?)
        # match everything lazily and capture it in a group called content
        ::
        # two colons 
        (?=\/)
        # closing tag with tag captured in group 1
        ~x';
preg_match_all($regex, $string, $matches);
print_r($matches["content"]);
/* output:
Array
(
    [0] => gx
    [1] => Lorem
    [2] => ipsum
    [3] => dolor, fithos lusec.
    [4] => 
    [5] => gx
    [6] => calendar
    [7] => 1 Fatura Grátis Por Ano
)
*/
?>