2014-12-09 47 views
1

我有一個具有如此多href屬性的文件。我想修改路徑,只想添加現有的絕對路徑。 例如href="parentall_files/filelist.xml",只需在整個文件中改爲href="dir/parentall/parentall_files/filelist.xml"。 我寫了以下內容:在php中使用href路徑連接字符串

$contents = preg_replace('/<a href="(.*?)"/i', '<a href="dir\/parentall\/$"',$contents); 

但是唉!它不會改變路徑。 請幫忙。

回答

1

爲什麼你不只是str_replace()

$contents = str_replace('href="parentall_files/','href="dir/parentall/parentall_files/', $contents); 
+0

您好CodeingInsane, 我試過這個,但我認爲我犯了一些愚蠢的錯誤。首先我使用file_get_contents(「html_file_path_here」); 然後替換href屬性的路徑,然後最後回顯內容。這樣對嗎? – Srim 2014-12-09 12:06:05

+0

非常感謝。這是工作。其實,我犯了一個錯誤,我應該替換href以及src – Srim 2014-12-09 12:27:08

0

嘗試

preg_replace('/<a href="(.*?)"/', '<a href="dir\/parentall\/"',$contents) 
0

您需要添加{1}$標誌

$string = '<a href="parentall_files/filelist.xml">asdsadsad</a>'; 
$new = preg_replace('/<a href="(.*?)"/i', '<a href="dir/parentall/${1}', $string); 

輸出變化是:

string '<a href="dir/parentall/parentall_files/filelist.xml>asdsadsad</a>' (length=65)