preg_replace_callback

Supported Versions: PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8
Perform a regular expression search and replace using a callback
<?php preg_replace_callback(    string|array $pattern,    callable $callback,    string|array $subject,    int $limit = -1,    int &$count = null,    int $flags = 0): string|array|null
<?php         return $files->map(function($file) use ($pattern, $replacement) {

            if($replacement instanceof Closure) {

                $file['content'] = preg_replace_callback($pattern, $replacement, $file['content'], -1, $count);

            } else {

                $file['content'] = preg_replace($pattern, $replacement, $file['content'], -1, $count);

            }
<?php     static function replaceDynamicPlaceholders($event, $component)

    {

        return preg_replace_callback('/\{(.*)\}/U', function ($matches) use ($component) {

            return data_get($component, $matches[1], function () use ($matches) {

                throw new \Exception('Unable to evaluate dynamic event name placeholder: '.$matches[0]);

            });

        }, $event);

    }

}
<?php     static function replaceDynamicPlaceholders($key, $component)

    {

        return preg_replace_callback('/\{(.*)\}/U', function ($matches) use ($component) {

            return data_get($component, $matches[1], function () use ($matches) {

                throw new \Exception('Unable to evaluate dynamic session key placeholder: '.$matches[0]);

            });

        }, $key);

    }

}
<?php     {

        $pattern = '/'.Regexes::$livewireOpeningTagOrSelfClosingTag.'/x';



        return preg_replace_callback($pattern, function (array $matches) {

            $attributes = $this->getAttributesFromAttributeString($matches['attributes']);



            $keys = array_keys($attributes);

            $values = array_values($attributes);

            $attributesCount = count($attributes);



            for ($i=0; $i < $attributesCount; $i++) {

                if ($keys[$i] === ':' && $values[$i] === 'true') {

                    if (isset($values[$i + 1]) && $values[$i + 1] === 'true') {

                        $attributes[$keys[$i + 1]] = '$'.$keys[$i + 1];

                        unset($attributes[':']);

                    }

                }

            }




            $attributes = collect($attributes)->mapWithKeys(function ($value, $key) {


                if (str($key)->contains('_')) return [$key => $value];



                return [(string) str($key)->camel() => $value];

            })->toArray();





            $attributes = collect($attributes)->mapWithKeys(function ($value, $key) {


                if (! str($key)->contains('_')) return [$key => false];



                return [(string) str($key)->camel() => $value];

            })->filter()->merge($attributes)->toArray();



            $component = $matches[1];



            if ($component === 'styles') return '@livewireStyles';

            if ($component === 'scripts') return '@livewireScripts';

            if ($component === 'dynamic-component' || $component === 'is') {

                if (! isset($attributes['component']) && ! isset($attributes['is'])) {

                    throw new ComponentAttributeMissingOnDynamicComponentException;

                }




                $component = $attributes['component'] ?? $attributes['is'];



                unset($attributes['component'], $attributes['is']);

            } else {


                $component = "'{$component}'";

            }



            return $this->componentString($component, $attributes);

        }, $value);

    }



    protected function componentString(string $component, array $attributes)
<?php     public function livewire_only_precompilers_apply_to_livewire_components_and_not_normal_blade()

    {

        Livewire::precompiler(function ($string) {

            return preg_replace_callback('/@foo/sm',  function ($matches) {

                return 'bar';

            }, $string);

        });



        $output = Blade::render('
<?php         $pattern = "/,\s*?key\(([\s\S]*)\)/"; // everything between ",key(" and ")"



        $expression = preg_replace_callback($pattern, function ($match) use (&$key) {

            $key = trim($match[1]) ?: $key;

            return "";

        }, $expression);



        if (! $key) {

            $key = app(\Livewire\Mechanisms\ExtendBlade\DeterministicBladeKeys::class)->generate();
<?php     protected function formatKey($key)

    {

        return preg_replace_callback(

            '/(.*)\.(.*)$/', fn ($matches) => sprintf(

                '<fg=gray>%s ⇁</> %s',

                str_replace('.', ' ⇁ ', $matches[1]),

                $matches[2]

            ), $key

        );

    }
<?php     {

        $path = $this->replaceNamedParameters($path, $parameters);



        $path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) {


            $parameters = array_merge($parameters);



            return (! isset($parameters[0]) && ! str_ends_with($match[0], '?}'))

                        ? $match[0]

                        : Arr::pull($parameters, 0);

        }, $path);



        return trim(preg_replace('/\{.*?\?\}/', '', $path), '/');

    }
<?php     protected function replaceNamedParameters($path, &$parameters)

    {

        return preg_replace_callback('/\{(.*?)(\?)?\}/', function ($m) use (&$parameters) {

            if (isset($parameters[$m[1]]) && $parameters[$m[1]] !== '') {

                return Arr::pull($parameters, $m[1]);

            } elseif (isset($this->defaultParameters[$m[1]])) {

                return $this->defaultParameters[$m[1]];

            } elseif (isset($parameters[$m[1]])) {

                Arr::pull($parameters, $m[1]);

            }



            return $m[0];

        }, $path);

    }
<?php     function preg_replace_array($pattern, array $replacements, $subject)

    {

        return preg_replace_callback($pattern, function () use (&$replacements) {

            foreach ($replacements as $value) {

                return array_shift($replacements);

            }

        }, $subject);

    }

}
<?php     public static function replaceMatches($pattern, $replace, $subject, $limit = -1)

    {

        if ($replace instanceof Closure) {

            return preg_replace_callback($pattern, $replace, $subject, $limit);

        }



        return preg_replace($pattern, $replace, $subject, $limit);
<?php     public function replaceMatches($pattern, $replace, $limit = -1)

    {

        if ($replace instanceof Closure) {

            return new static(preg_replace_callback($pattern, $replace, $this->value, $limit));

        }



        return new static(preg_replace($pattern, $replace, $this->value, $limit));
<?php     protected function storeVerbatimBlocks($value)

    {

        return preg_replace_callback('/(?<!@)@verbatim(\s*)(.*?)@endverbatim/s', function ($matches) {

            return $matches[1].$this->storeRawBlock($matches[2]);

        }, $value);

    }
<?php     protected function storePhpBlocks($value)

    {

        return preg_replace_callback('/(?<!@)@php(.*?)@endphp/s', function ($matches) {

            return $this->storeRawBlock("<?php{$matches[1]}?>");

        }, $value);

    }
<?php     protected function restoreRawContent($result)

    {

        $result = preg_replace_callback('/'.$this->getRawPlaceholder('(\d+)').'/', function ($matches) {

            return $this->rawBlocks[$matches[1]];

        }, $result);



        $this->rawBlocks = [];