我正在尝试使用额外的字符串(如“/testing123”等)在 RSS 提要中附加所有 url。来自 RSS 的原始 url 格式如下所示:
<link rel="alternate" type="text/html" href="http://website.com/item/name1/2162561"/>
<link rel="alternate" type="text/html" href="http://website.com/item/name2/2162435"/>
等等,我在 for 循环中使用了带有 str_replace 的正则表达式,但我似乎无法让它正常工作,如果我使用 preg_replace 我会出错。当我只是回显带有附加字符串的网址时,它会显示我想要的方式,但是当我使用 str_replace 时,网址看起来像这样:
http://website.com/testing123/item/name1/2162561
http://website.com/testing123/item/name2/2162435
当它们被替换时,我需要在末尾带有附加字符串的 url,但是像这样:
<link rel="alternate" type="text/html" href="http://website.com/item/name1/2162561/testing123"/>
<link rel="alternate" type="text/html" href="http://website.com/item/name2/2162435/testing123"/>
我的代码是:
<?php
// The append string
$append = '/testing123';
// The file
$file = "RSS.txt";
// Get the files contents
$contents = file_get_contents($file);
// The search pattern
$SearchPattern = '/href=["|\'](.[^"|\']+)/i';
// Run preg_match_all to grab all the Matches
preg_match_all( $SearchPattern, $contents, $Matches );
// Check to see if we have at least 1 match
$MatchCount = count($Matches[0]);
// If there is more than 1 match then run a for loop
if ( $MatchCount > 0 ) {
for ( $i=0; $i < $MatchCount ; $i++ ) {
$temp = $Matches[0][$i];
echo $temp . $append . '<br />'; // Appears to work
//$contents = str_replace($temp, $temp . $append, $contents); // But str_replace doesn't seem to work
//preg_replace($temp, $temp . $append, $contents); // And using preg_replace gives a error
};
};
echo $contents; // Display the contents
?>