我已经用这一行获得了一个页面php:
$url = file_get_contents('http://web.com/rss.php');
现在我要替换它:
<link>http://web.com/download/45212/lorem-ipsum</link>
<link>http://web.com/download/34210/dolor-sit</link>
<link>http://web.com/download/78954/consectetur-adipiscing</link>
<link>http://web.com/download/77741/laboris-nisi</link>
...
有了这个:
<link>http://otherweb.com/get-d/45212</link>
<link>http://otherweb.com/get-d/34210</link>
<link>http://otherweb.com/get-d/78954</link>
<link>http://otherweb.com/get-d/77741</link>
...
我已用str_replace
替换了部件,但我不知道要替换其他部件。
这就是我现在所做的:
$url = str_replace('<link>http://web.com/download/','<link>http://otherweb.com/get-d/', $url);
答案 0 :(得分:2)
你可以用一行正则表达式完成所有这些:)
<强>正则表达式强>
以下正则表达式将检测您的中间编号部分....
<link>http:\/\/web\.com\/download\/(.*?)\/.*?<\/link>
<强> PHP 强>
要在PHP中使用这个,你可以使用这行代码
$url = preg_replace("/<link>http:\/\/web\.com\/download\/(.*?)\/.*?<\/link>/m", "<link>http://otherweb.com/get-d/$1</link>", $url);
这应该完全符合你的需要!
<强>解释强>
它的工作方式是preg_replace
在开始时查找<link>http://web.com/download/
,在结尾查找/{something}</link>
。它将中间区域捕获到$1
因此,当我们运行preg_replace ($pattern, $replacement, $subject)
时,我们告诉PHP只找到中间部分(您的网址中的数字)并将其嵌入"<link>http://otherweb.com/get-d/$1</link>"
。
我测试了它,它似乎正在工作:)
编辑:我建议这个答案最适合你,因为它只用一行做所有事情,并且不需要任何str_replace
。即使中间部分是字母数字,我的答案也会起作用,而且不仅仅是数字。
答案 1 :(得分:2)
您要做的就是:
$input = 'http://web.com/download/45212/lorem-ipsum'; echo preg_replace('/.*\/(\d+).*/', 'http://otherweb.com/get-d/$1', $input);
要提取相关部分,您可以使用(\d+)
,这意味着:查找一个或多个数字,括号将其设为匹配组,以便您可以通过$1
访问此值。
要匹配并替换整行,您必须在.*
部分之前和之后使用(\d+)
(这意味着,查找任意数量的任何字符)来扩充模式。
通过此设置,整个字符串匹配,因此整个字符串将被替换。
答案 2 :(得分:0)
你只是缺少一个简单的正则表达式来清理最后一部分。
我是这样做的:
$messed_up = '
<link>http://web.com/download/45212/lorem-ipsum</link>
<link>http://web.com/download/34210/dolor-sit</link>
<link>http://web.com/download/78954/consectetur-adipiscing</link>
<link>http://web.com/download/77741/laboris-nisi</link>';
// Firstly we can clean up the first part (like you did) with str_replace
$clean = str_replace('web.com/download/','otherweb.com/get-d/', $messed_up);
// After that we'll use preg_replace to get rid of the last part
$clean = preg_replace("/(.+\/\d+)\/.*(<.*)/", "$1$2", $clean);
printf($clean);
/* Returns:
<link>http://otherweb.com/get-d/4521</link>
<link>http://otherweb.com/get-d/3421</link>
<link>http://otherweb.com/get-d/7895</link>
<link>http://otherweb.com/get-d/7774</link>
*/
我很快就这样做了,所以可能还有一些改进空间,但它确实有效。
您可以查看实践中的代码HERE。
如果您有兴趣学习PHP RegEx This是一个很好的练习场所。
答案 3 :(得分:0)
您应该使用token
替换链接的初始部分,然后preg_replace字符串的结尾,搜索第一个/
并替换为</link>
。所以你用你想要的初始部分替换你的标记。
$url = str_replace('<link>http://web.com/download/','init', $url);
$url = preg_replace("/\/.+/", "</link>", $url);
$url = str_replace('init', '<link>http://otherweb.com/get-d/', $url);