【发布时间】:2012-10-18 16:50:01
【问题描述】:
我在执行以下操作时遇到了一些问题..
http://www.google.com --> www.google.com/
https://google.com --> www.google.com/
google.com --> www.google.com/
我正在尝试删除https:// or http://,确保将www. 添加到URL 的开头,然后在URL 不存在的情况下添加尾部斜杠。
感觉我已经弄清楚了其中的大部分,但我无法让 str_replace() 按我的意愿工作。
据我了解,这是str_replace的使用方法:
$string = 'Hello friends';
str_replace('friends', 'enemies', $string);
echo $string;
// outputs 'Hello enemies' on the page
这是我目前所拥有的:
$url = 'http://www.google.com';
echo reformat_url($url);
function reformat_url($url) {
if ( substr( $url, 0, 7 ) == 'http://' || substr( $url, 0, 8 ) == 'https://' ) { // if http:// or https:// is at the beginning of the url
$remove = array('http://', 'https://');
foreach ( $remove as $r ) {
if ( strpos( $url, $r ) == 0 ) {
str_replace($r, '', $url); // remove the http:// or https:// -- can't get this to work
}
}
}
if ( substr( $url, 0, 4 ) != 'www.') { // if www. is not at the beginning of the url
$url = 'www.' . $url; // prepend www. to the beginning
}
if ( substr( $url, -1 ) !== '/' ) { // if trailing slash does not exist
$url = $url . '/'; // add trailing slash
}
return $url; // return the formatted url
}
对于格式化 URL 的方式的任何帮助将不胜感激;我也很好奇我在使用 str_replace 删除 http:// 或 https:// 时做错了什么。如果有人能提供一些关于我做错了什么的见解,我们将不胜感激。
【问题讨论】:
-
不,这不是你应该使用
str_replace的方式。 -
谢谢 Alvin,我误解了如何使用它。我现在明白它不会修改您提供给它的主题参数。
标签: php url str-replace substr