我只想使用preg_replace()
将绝对服务器转换为相对url。但我的正则表达式知识为零。我该怎么做?
示例:
<a href="http://mysite.localhost.com/admin/structure">Some text</a>
至
<a href="/admin/structure">Some text </a>
谢谢。
使用PHP的str_replace()函数可以更快地完成此操作。即:
$href = str_replace('http://mysite.localhost.com', '', $href);
一个优点是,与preg_replace()相比,str_replace()在服务器上的开销要小得多。
这将把<a>
标签中的每个绝对链接变成一个相对链接:
<?php
$html = '<a href="http://mysite.localhost.com/admin/structure">Some text</a>';
echo preg_replace('#<a ([^'>]+)href=["'']?https?://[^/]+(/[^'s]+)["'']?([^'>]+)>#i', '<a $1href="$2"$3>', $html);
返回<a href="/admin/structure">Some text</a>