用PHP查找并替换字符串中的关键字



我有这个代码来查找和替换一些字符串,如果它在一些{{}}之间。

$string = 'This is my {{important keyword}}.';
$string = preg_replace('/{{(.*?)}}/', '<a href="$1">$1</a>', $string);
return $string;

我如何改变<a href="$1">$1</a>部分有这样的东西:

<a href="https://example.com/important-keyword">important keyword</a>

因此,href需要将match项目转换为一个单元格(用破折号分隔的单词,没有重音或特殊字符)。

谢谢。

您必须使用preg_replace_callback()来允许在函数中更改匹配。

参见use($url)允许函数访问外部变量。

代码:


$url = 'https://example.com';
$string = 'This is my {{important keyword}}.';
$string = preg_replace_callback('/{{(.*?)}}/', function($matches) use ($url) {
$newURL = $url . '/' . str_replace(' ', '-', $matches[1]);
return '<a href="' . $newURL . '">' . htmlentities($matches[1]) . '</a>';
}, $string);
echo $string;

输出:

This is my <a href="https://example.com/important-keyword">important keyword</a>.

最新更新