Search code examples
phpregexpreg-match

PHP Preg Match, get value between specific pattern


I have a php application that saves the following output on database:

::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::

And I want to retrieve information from this output using preg_match. For example retrieving any value in the same place of "Lorem" and "ipsum" on the example below:

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

But I am clueless with preg_match syntax.

I understand that I will need a different preg match for each "label" (like a preg_match to retrieve all "i1" values, a different preg_match to retrieve all "head1" and so on). I just need one example that works to understand the correct pattern.

Also, in the last line is a example with a lot of different characters like numbers, commas, "%" and others, I am not sure if this will mess with syntax.

Here two of my failed attempts:

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);

Solution

  • Hope this will help

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

    You can also use 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 Lookbehind - Assert that the regex below can be matched

    . matches any character (except newline)

    * Between zero and unlimited times, as many times as possible

    (?=::\/) Positive Lookahead - Assert that the regex below can be matched

    :: matches the characters :: literally

    \/ matches the character / literally