Reputation: 11988
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?
Upvotes: 0
Views: 33
Reputation: 54831
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].');
Upvotes: 2