在我的網站內容中有一些沒有尾隨「/」的內部鏈接,它對我造成了一些抓取問題。想要進行搜索並替換這些鏈接。所以https://www.example.com/slug應該變成https://www.example.com/slug/。我使用下面的函數來推動一個頁面在整個視頻內容和替換頁面上的所有必要的鏈接:將斜槓添加到preg_replace的鏈接
function str_replace_links($subject, &$count) {
//match the first part of the link http://www.example.com{/slug}
$regex = '/(https:\/\/www.example.com)(\/[a-zA-Z_0-9\-]*)*';
//check for the trailing '/' or if it is a file
$regex .= '([^(\/|\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.torrent|\.ttf|\.woff|\.svg|\.eot|\.woff2)])';
//finish ooff regex
$regex .= '/i';
$i; // counter for # changed
$content = preg_replace($regex, '$1$2/', $subject, 1, $i);
$count += $i;
return $content;
}
我試圖測試一個字符串幾個環節:
$string ='
<a href="https://www.example.com/slug1/page">1</a><br/>
<a href="https://www.example.com/slug2/page">2</a><br/>
<a href="https://www.example.com/slug1/page/">3</a><br/>
<a href="https://www.example.com/slug2/page/">4</a><br/>
<a href="https://www.example.com/">5</a><br/>
<a href="https://www.example.com">5b</a><br/>
<a href="https://www.example.com/style.css">6</a><br/>
<a href="https://www.example.com/style.jpg">7</a><br/>
<a href="https://www.example.com/style.png">8</a><br/>
<a href="https://www.example.com/style.pdf">9</a><br/>
';
echo str_replace_links($string, $switch);
然而,這不會導致正確的結果:
<a href="https://www.example.com/page/>1</a><br/>
<a href="https://www.example.com/page/>2</a><br/>
<a href="https://www.example.com//>3</a><br/>
<a href="https://www.example.com//>4</a><br/>
<a href="https://www.example.com//>5</a><br/>
<a href="https://www.example.com/>5b</a><br/>
<a href="https://www.example.com/st/le.css">6</a><br/>
<a href="https://www.example.com/st/le.jpg">7</a><br/>
<a href="https://www.example.com/st/le.png">8</a><br/>
<a href="https://www.example.com/st/le.pdf">9</a><br/>
任何與正則表達式的幫助將不勝感激。
真棒!謝謝 – jppower175