0

I want to parse:

My name is [name]Bob[/name] and her name is [name]Mary[/name].

into:

My name is {{ $name[1] }} and her name is {{ $name[2] }}.

and:

public function parse($string)
{
    $pattern = '~\[name\](.*?)\[/name\]~s';

    $matches = preg_match_all($pattern, $string);

    for($i = 1; $i <= $matches; $i++)
    {
        $result[] = '{{ $name['. $i .'] }}';
    }

    return implode(' ', $result);
}

returns:

{{ $name[1] }} {{ $name[2] }}

Question: How do I add this to my string to get the desired result?

1
  • preg_replace_callback Commented Nov 17, 2020 at 15:44

1 Answer 1

2

With preg_replace_callback it is:

function parse($string)
{
    $pattern = '~\[name\](.*?)\[/name\]~s';
    $i = 1;

    return preg_replace_callback(
        $pattern, 
        function ($m) use (&$i) {
            return '{{ $name['. $i++ .'] }}';
        },
        $string, 
    );
}

echo parse('My name is [name]Bob[/name] and her name is [name]Mary[/name].');

Fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Works! Found a different solution (3v4l.org/rNsOO) but I think I'll stick with yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.