温馨提示×

php preg_replace_callback 的最佳实践案例

PHP
小樊
92
2024-06-24 20:13:27
栏目: 编程语言
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

以下是一个使用preg_replace_callback函数的最佳实践案例:

$text = "Hello, my name is [NAME] and I am a [JOB].";
$replacements = array(
    'NAME' => 'John',
    'JOB' => 'developer'
);

$newText = preg_replace_callback('/\[([A-Z]+)\]/', function($matches) use ($replacements) {
    $key = $matches[1];
    return isset($replacements[$key]) ? $replacements[$key] : $matches[0];
}, $text);

echo $newText; // Output: Hello, my name is John and I am a developer.

在这个示例中,我们首先定义了一个包含替换值的关联数组$replacements。然后,我们使用preg_replace_callback函数来查找文本中的匹配项,并将其替换为相应的值。回调函数接收一个匹配数组$matches作为参数,并根据匹配的键来查找替换值。最后,我们得到了新的文本$newText,其中[NAME]被替换为John,[JOB]被替换为developer。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:为什么 php preg_replace_callback 这么强大

0