编程语言
首页 > 编程语言> > PHP file_get_contents-替换所有链接中的所有URL

PHP file_get_contents-替换所有链接中的所有URL

作者:互联网

解决:下面的答案

如何:
 -从使用file_get_contents提取的文件中获取所有网址.该文件可以动态并且具有多个URL
 -将所有网址替换为自定义A新网址,最后将现有的当前网址添加为变量

例:

将链接www.ABC.com更改为www.MyWebsite.com/?link=www.ABC.com

文件名:myHTML.html
将使用file_get_contents提取的HTML电子邮件

<body>
<p>&nbsp;</p>
<p><a href="http://www.CNN.com" target="_blank">Link One</a></p>
<p><a href="http://www.ABC.com" target="_blank">Link Two</a></p>
<p><a href="http://www.foxnews.com/politics/2013/01/28/us-planning-for-new-drone-base-in-northwest-africa-officials-say/" target="_blank">Link Three</a></p>
<p><a href="ObamaMustSee.com" target="_blank">Link Four</a></p>
</body>

需要输出到以下代码:

 <body>
<p>&nbsp;</p>
<p><a href="http://www.MyWebsite.com/?link=http://www.CNN.com" target="_blank">Link One</a></p>
<p><a href="http://www.MyWebsite.com/?link=http://www.ABC.com" target="_blank">Link Two</a></p>
<p><a href="http://www.MyWebsite.com/?link=http://www.foxnews.com/politics/2013/01/28/us-planning-for-new-drone-base-in-northwest-africa-officials-say/" target="_blank">Link Three</a></p>
<p><a href="http://www.MyWebsite.com/?link=ObamaMustSee.com" target="_blank">Link Four</a></p>
</body>

下面对我有用的答案!
附: 1如果这对您有帮助:)

解决方法:

这段代码将从给定的字符串中提取所有HTTP url,并将它们放入数组,以便您可以执行要从数组链接的任何操作:

<?php
$string = "Test http://www.google.com test2 http://www.something.com test3 http://abc.com";
preg_match_all('!https?://[\S]+!', $string, $match);

$URLs = array();

foreach ($match as $key => $value)
    foreach ($value as $key2 => $TheUrl)
        $URLs[] = $TheUrl;


for ($i=0;$i<count($URLs);$i++)
    echo $URLs[$i]."\r\n";

?>

现在,您已经将$string变量中给定的string中的所有URL放入$URLs数组中.您可以print_r URLs数组以查看其内容,也可以使用for循环遍历它(如我的示例所示).

现在,如果要替换字符串中的所有URL,可以执行以下操作:

for ($i=0;$i<count($URLs);$i++)
    $string = str_replace($URLs[$i], "http://www.mysite.com?newurl=".$URLs[$i], $string);

例如,它将所有URL字符串替换为http://www.mysite.com?newurl=[ACTUAL URL]

标签:file-get-contents,php,arrays,html-email
来源: https://codeday.me/bug/20191012/1902526.html