我使用 str_replace 将 URL 重写为 PDF,从 https://example.com/documents/en/whatever.PDF 到 https://example.com/documents/es/whatever_SPANISH.pdf
我用的就是这个
if($_COOKIE['googtrans'] == "/en/es") { //Check the google translate cookie
$text = str_replace('/documents/en/', '/documents/es/', $text);
$text = str_replace('.pdf', '_SPANISH.pdf', $text);
}
问题是,如果页面包含链接到另一个页面(不是我自己的网站)的 PDF,例如 https://othersite.example.com/whatever.pdf,它就会变成 https://othersite.example。 com/whatever_SPANISH.pdf 在其他人的网站上无效。我想忽略站外链接,只更改我网站上的 URL。
所以我想做的是寻找字符串: https://example.com/documents/en/whateverfilename.pdf 取出该文件名并将其更改为 https://example.com/documents/es/whateverfilename_SPANISH.pdf (将 en 切换为 es,并将 _SPANISH 附加到 PDF 文件名的末尾。
我该怎么办呢。尝试过各种 preg_replace 但无法让我的语法正确。
if($_COOKIE['googtrans'] == "/en/es") {
$text = str_replace('/documents/en/', '/documents/es/', $text);
$text = str_replace('.pdf', '_SPANISH.pdf', $text);
}
您可以在替换中使用正则表达式和 2 个捕获组值一次性完成替换。
查看正则表达式组捕获。
$regex = '~\b(https?://\S*?/documents/)en(/\S*)\.pdf\b~';
$text = "https://example.com/documents/en/whateverfilename.pdf";
$subst = "$1es$2_SPANISH.pdf";
$result = preg_replace($regex, "$1es$2_SPANISH.pdf", $text);
echo $result;
输出
https://example.com/documents/es/whateverfilename_SPANISH.pdf