Home > Back-end >  PHP Regex create something like liquid tags
PHP Regex create something like liquid tags

Time:11-13

I'm trying to parse something like this

{%github user/repo %}

Into

<a href="https://github.com/user/repo">Repo</a>

This method also should be secure ex: Look below my function.

function parseliquid($string)
{
    $randhashtoreplace = md5(rand(0, 9999));
    $regexp = '/\{%github (.*?)%\}/';
    $str = preg_replace($regexp, $randhashtoreplace, $string);

    preg_match($regexp, $string, $matches);
    return $matches;
}


var_dump(parseliquid("## Hello {%github isn't/safe {%github repo/user %} %}"));

Now the expected output is

array(2) {
  [0]=>
  string(41) "{%github isn't/safe {%github repo/user %}"
  [1]=>
  string(9) "repo/user"
}

but the output that comes is

array(2) {
  [0]=>
  string(41) "{%github isn't/safe {%github repo/user %}"
  [1]=>
  string(30) "isn't/safe {%github repo/user "
}

Now what have I done wrong?

CodePudding user response:

You can try this code

<?php

function getRepositoryNames(string $value): array
{
    \preg_match_all('/\{\%github\s(?<repo>[a-z0-9-_] \/[a-z0-9-_] )\s /', $value, $matched);

    if (!isset($matched['repo'])) {
        return [];
    }

    return \array_map(static fn ($item) => 'https://github.com/'.$item, $matched['repo']);
}

\var_dump(getRepositoryNames('{%github isnt/safe {%github repo/user1-test %}'));
/*
 array(2) {
  [0]=>
  string(28) "https://github.com/isnt/safe"
  [1]=>
  string(34) "https://github.com/repo/user1-test"
}
 */

Documentation:

https://www.php.net/manual/en/function.preg-match.php - Use Example #4

Tested Regex you can this https://regexr.com/

  • Related