问题描述
我在 $url 中有两个 URL 模式结构
I have two URL patten structure in $url
- news.oxo.com/site/data/html_dir/2013/05/25/2013052500007.html
- salute.com/arti/society/health/588947.html
并希望将它们更改为
- m.oxo.com/article.html?contid=2013052500007
- m.salute.com/article.html?contid=2013052500007
我试过了
<?php $url_m = preg_replace("salute.com","m.salute.com",$url); ?>
<?php echo $url_m; ?>
我想我完全迷路了-_-;;;;
And I guess I am totally lost -_-;;;;
任何帮助都可能受到高度赞赏.
Any help might be highly appreciated.
推荐答案
如果您负责这两个 URL 并且正在使用 Apache,您可以使用 .htaccess
处理旧 Apache 服务器中的旧地址:
If you're responsible for both URLs and are using Apache you can handle the old addresses in the old Apache server with .htaccess
:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^news.oxo.com$
RewriteRule ^site/data/html_dir/[0-9]{4}/[0-9]{2}/[0-9]{2}/([0-9]+)\.html$ http://m.oxo.com/article.html?contid=$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^(www\.)?salute.com$
RewriteRule ^[^/]+/[^/]+/[^/]+/([0-9]+)\.html$ http://m.salute.com/article.html?contid=$1 [R=301,L]
如果您不负责任并且只想在 PHP 中重写 URL(例如,如果您要更改数据库中的链接),您可以这样做:
If you're not responsible and are only wanting to rewrite the URLs in PHP (if you're changing a link from a database for example), you would do this:
<?php
$original_URLs[0] = "news.oxo.com/site/data/html_dir/2013/05/25/2013052500007.html";
$original_URLs[1] = "salute.com/arti/society/health/588947.html";
//patterns for m.oxo
$replacements[0] = 'm.oxo.com/article.html?contid=$1';
$patterns[0] = "!news.oxo.com/site/data/html_dir/[0-9]{4}/[0-9]{2}/[0-9]{2}/([0-9]+)\.html$!";
//patterns for m.salute
$replacements[1] = 'm.salute.com/article.html?contid=$1';
$patterns[1] = '!salute\.com/[^/]+/[^/]+/[^/]+/([0-9]+)\.html$!';
foreach($original_URLs as $key=>$url){
echo "<pre>".preg_replace($patterns,$replacements,$url)."</pre>";
}
?>
如果您尝试替换嵌入在文章等内容中的链接,也可以使用字符串替换来替换 foreach.
You can also replace the foreach with a string replacement as well if you're trying to replace links embedded in something like an article.
echo "preg_replace($patterns,$replacements,$some_article);
这篇关于PHP preg_match URL 替换用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!