2017-07-18 53 views
0

一个字符串包含各种URL是这样的:在字符串替换特定URL用PHP

http://www.example.com/viewtopic.php?f=36&t=457 
http://www.example.com/viewtopic.php?f=36&t=11782 

实施例用1个URL:

Lorem ipsum dolor sit amet, http://www.example.com/viewtopic.php?f=36&t=457 consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. 

实施例2的URL

Lorem ipsum dolor sit amet, http://www.example.com/viewtopic.php?f=36&t=457 consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. http://www.example.com/viewtopic.php?f=36&t=11782 At vero eos et accusam et justo duo dolores et ea rebum. 

本文中的网址不要被新的seo网址取代。

http://www.example.com/viewtopic.php?f=36&t=457 

变得

http://www.example.com/this-ist-the-new-url.html 

SEO的网址将通过函数generatred。

怎么可能搜索和一个字符串内其他网址取代完整的URL当URL包含此:

http://www.example.com/viewtopic.php 

非常感谢你。

+0

我相信你要寻找的“网址重写规则“。看看这篇文章。 https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/ – IsThisJavascript

+0

嗨,不,我知道如何重写。我已经有了一个功能。我正在寻找一个函数来用新的URL替换URL。谢谢 – labu77

回答

0

以下功能正在寻找字符串中的完美匹配。只要给定的字符在那里,只要字符串前后有字符就没有关系。

$phrase = "Whatever you write here it can be replaced"; 
$replacethis = array("you", "can", "replaced"); 
$withtis = array("I", "can't", "placed"); 

$newphrase = str_replace($replacethis, $whithis, $phrase); 

而且$newphrase是:不管我写这里不能放置

你的情况,那就是:

$phrase = "Whatever you write here it can be replaced"; 
$replacethis = array("http://www.example.com/viewtopic.php?f=36&t=457"); 
$withtis = array("http://www.example.com/this-ist-the-new-url.html"); 

$newphrase = str_replace($replacethis, $whithis, $phrase); 
+0

嗨,谢谢。我知道str_replace如何工作。问题在于URL是多种多样的。所以没有完全匹配。 – labu77

+0

好吧。使用[this](http://tools.buzzstream.com/link-building-extract-urls)这样的工具从网页中提取网址。之后,您将获得一个列表,您可以使用它来创建一个for循环单独替换网址。 –