PHP删除所有href和src中的..斜杠


php remove dot dot slash from all href and src

我正在制作一个需要相关链接的html模板,但对于模板,我必须使用php(非常noob),在索引文件中,我想从href和src中删除所有../,就像这个例子:

page.php
scr="../img/image.jpg"
href="../contact/contact.php"
index.php
scr="img/image.jpg"
href="contact/contact.php"

如何创建一个函数来删除所有的../

谢谢

如果真的是这样,../只在开始出现一次,下面将工作:

echo str_replace('../', $string);

如果路径中间可能存在不应该清除的../,则使用preg_replace():

$str = '../img/image.jpg';
echo preg_replace('~^('.'./)(.*)$~', "$2", $str);

我使用get_file_contents读取模板,然后替换字符串:

$sContents = file_get_contents('<URL TO FILE>');
$sContents = str_replace('../', '', $sContents);