我有成千上万的PHP页面,其中包含使用php的页眉和页脚,如
<?php include("header.php"); ?> //STATIC CONTENT HERE <?php include("footer.php"); ?>
Run Code Online (Sandbox Code Playgroud)
我想为静态文本中的某些关键字实现自动关键字链接.但我只能将PHP代码添加到我的页眉或页脚文件中.
这可能是一项复杂的操作.步骤:
glob)glob替换文本来迭代返回的文件(preg_replace)file_put_contents)此示例代码用$words链接替换数组中的所有单词http://www.wordlink.com/<yourword>.如果您需要为每个单词指定不同的链接,则需要指定$replace为数组,使用$1您希望搜索的单词出现在替换中的位置(并将$replace正则表达式更改为$replace[$i]).
此外,glob下面的函数查找指定$filesDir目录中的所有html文件.如果您需要不同的东西,则必须自己手动编辑glob路径.最后,使用的正则表达式仅替换整个单词.即如果你想替换单词super,单词superman将不会在中间替换super.
哦,根据模式结尾处的修饰符,替换不区分大小写i.
// specify where your static html files live
$filesDir = '/path/to/my/html/files/';
// specify where to save your updated files
$newDir = '/location/of/new/files/';
// get an array of all the static html files in $filesDir
$fileList = glob("$filesDir/*.html");
$words = array('super', 'awesome');
$replace = '<a href="http://www.wordlink.com/$1">$1</a>';
// iterate over the html files.
for ($i=0; $i < count($fileList); $i++) {
$filePath = $filesDir . $fileList[$i];
$newPath = $newDir . $fileList[$i];
$html = file_get_contents($filePath);
$pattern = '#\b(' . str_replace('#', '\#', $words[$i]) . ')\b#i';
$html = preg_replace($pattern, $replace, $html);
file_put_contents($newPath, $html);
echo "$newpath file written\n";
}
Run Code Online (Sandbox Code Playgroud)
显然,您需要对新文件夹位置的写访问权限.我不建议覆盖原始文件.翻译:
PS正则表达式不是UTF-8安全的,所以如果你正在处理国际字符,你也需要编辑正则表达式模式.
PPS我真的很善良,因为SO 不是免费的代码网站.当我尝试它时,甚至不要考虑评论"它不起作用"的东西:)如果它不符合您的规格,请随意浏览所涉及的功能的PHP手册.