小兔网

php实现相对路径转绝对路径的方法:可以通过preg_replace()函数来实现。preg_replace()函数可以执行一个正则表达式的搜索和替换。若搜索目标是字符串数组,则该函数返回一个数组。

php如何实现相对路径转绝对路径

我们可以通过preg_replace()函数来实现相对路径转绝对路径。

(推荐学习:php教程

函数介绍

preg_replace() 函数执行一个正则表达式的搜索和替换。

函数语法

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

搜索 subject 中匹配 pattern 的部分, 以 replacement 进行替换。

参数说明:

  • $pattern: 要搜索的模式,可以是字符串或一个字符串数组。

  • $replacement: 用于替换的字符串或字符串数组。

  • $subject: 要搜索替换的目标字符串或字符串数组。

  • $limit: 可选,对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是-1(无限制)。

  • $count: 可选,为替换执行的次数。

返回值

如果 subject 是一个数组, preg_replace() 返回一个数组, 其他情况下返回一个字符串。

如果匹配被查找到,替换后的 subject 被返回,其他情况下 返回没有改变的 subject。如果发生错误,返回 NULL。

代码实现:

//相对路径转化成绝对路径<?function relative_to_absolute($content, $feed_url) { preg_match('/(http|https|ftp):///', $feed_url, $protocol); $server_url = preg_replace("/(http|https|ftp|news):///", "", $feed_url);//开源OSPhP.COM.CN$server_url = preg_replace("//.*/", "", $server_url);     if ($server_url == '') {         return $content;     }     if (isset($protocol[0])) {//开源代码OSPhP.COm.CN$new_content = preg_replace('/href="https://zhishitu.com/ke" 'href="https://zhishitu.com/ke" $content); $new_content = preg_replace('/src="//', 'src="'.$protocol[0].$server_url.'/', $new_content);  //开源OSPhP.COM.CN    } else { $new_content = $content;     }     return $new_content; } ?>

以上就是php如何实现相对路径转绝对路径的知识。速戳>>知识兔学习精品课!