替换标签之间 PHP 中的许多代码行

Replace many code lines in PHP between tags

我得到了一个页面 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);

您只是缺少一个简单的正则表达式来清理最后一部分。

这是我的做法:

$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+)\/.*(<.*)/", "", $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

If you're interested in learning PHP RegEx This is a great place to practice.

您应该将 link 的开头部分替换为 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);

你可以用一行正则表达式来完成这一切:)

正则表达式

下面的正则表达式将检测您的中间编号部分....

<link>http:\/\/web\.com\/download\/(.*?)\/.*?<\/link>

PHP

要在 PHP 中使用它,您可以使用这行代码

$url = preg_replace("/<link>http:\/\/web\.com\/download\/(.*?)\/.*?<\/link>/m", "<link>http://otherweb.com/get-d/</link>", $url);

这应该正是您所需要的!

说明

它的工作方式是 preg_replace 在开头查找 <link>http://web.com/download/,在结尾查找 /{something}</link>。它将中间区域捕获到 </code></p> <p>所以当我们 运行 <code>preg_replace ($pattern, $replacement, $subject) 时,我们告诉 PHP 只找到中间部分(您的 URLS 中的数字)并将它们嵌入 "<link>http://otherweb.com/get-d/</link>"

我测试了它,它似乎可以工作:)

编辑:我建议这个答案最适合您,因为它只用一行就可以完成所有事情,并且不需要任何 str_replace。即使中间部分是字母数字,我的答案也会起作用,而不仅仅是数字。

你想做的就是:

  1. 提取相关数据,例如五位数
  2. 将提取的部分放入新的上下文中
    $input = 'http://web.com/download/45212/lorem-ipsum';

    echo preg_replace('/.*\/(\d+).*/', 'http://otherweb.com/get-d/', $input);

要提取相关部分,你可以使用(\d+),这意味着:找到一个或多个数字,括号使它成为一个匹配组,所以你可以通过</code>访问这个值。</p> <p>要匹配和替换整行,您必须在 <code>(\d+) 部分前后用 .*(这意味着找到任意数量的任意字符)扩充模式。

通过此设置,整个字符串匹配,因此整个字符串将被替换。