preg-replace-如何使用PHP函数preg_replace()以网站URL命名.txt文件


preg replace - How do I use PHP Function preg_replace() in naming a .txt file after a site URL

如何在没有前面的https://http://的网站URL后命名txt文件,如:www.google.com.txt
我想我可能搞错了:fopen($sitenameWithoutHTTP.".txt, "w");

以下是我试图解决的方法:

<?php
//
@mkdir("result", 0755); 
@chdir("result");
$link = $sitename;
$sitename = preg_replace('#^https?://#', '', $sitenameWithoutHTTP);
$resultfile = fopen($sitenameWithoutHTTP.".txt", "w");
//
?>

感谢您帮助找到解决方案。

希望这能帮助您实现您的目标!

<?php
$siteName = 'https://www.google.com';
$siteNameWithoutHttps = preg_replace('#^https?://#', '', $siteName);
// print_r($siteNameWithoutHttps);
$resultFile = fopen($siteNameWithoutHttps.".txt", "w");
// run a check
if($resultFile == true) {
echo "success";
} else {
echo "failed";
}

上面注释的print_r的预期结果应该是:

www.google.com
$arr = ['http','https',':','/','?','&','#','.'];
$sitename = str_replace($arr, '', $sitenameWithoutHTTP);

也可以使用base64_encode()parse_url()

$HOST = parse_url($sitenameWithoutHTTP, PHP_URL_HOST);

如果你需要保存真实的URL并再次获得它,我认为使用Md5哈希的最佳方法

$fileName = md5($sitenameWithoutHTTP).'.txt';

可以再次获得file.php/?getFile2url=[httpLink]

header('Location: '. Md5($_GET['getFile2url']).'.txt');
exit;