【问题标题】:Replacing inside body using PHP [duplicate]使用 PHP 替换内部主体 [重复]
【发布时间】:2022-01-26 15:12:49
【问题描述】:

我正在尝试使用 PHP 替换内部正文标记,但每次我得到的输出都与我预期的不同。

试试:

$homepage = "<head>https://www.example.com</head> <body>https://www.example.com</body>";
$homepage = substr($homepage, strpos($homepage, "<body>"));
$homepage = preg_replace("/https:\/\/(.?)+\.example\.com/", "https://www.example.net", $homepage);
echo $homepage;

输出:

<head>https://www.example.net</body>

我正在寻找的输出:

<head>https://www.example.com</head> <body>https://www.example.net</body>

我只想更改/替换标签内的字符串。

【问题讨论】:

标签: php regex preg-replace domdocument str-replace


【解决方案1】:
  1. 头身分体
  2. 替换正文中的字符串
  3. 连接头部和身体

您的正则表达式有问题,我假设您想同时捕获 https://www.example.comhttps://example.com

这是您要查找的内容:

<?php

$homepage = '<head><link rel="stylesheet" type="text/css" href="https://www.example.com/whatever.css"></head><body>This link <a href="https://www.example.com">https://example.com</a> and this one <a href="https://www.example.com">https://www.example.com</a> will be replaced</body>';

$neck_pos = strpos($homepage, "<body");
$head = substr($homepage, 0, $neck_pos);
$body = substr($homepage, $neck_pos);


$body = preg_replace("/https:\/\/[w]*\.*example\.com/", "https://www.example.net", $body);

$homepage = $head . $body;

echo $homepage;

【讨论】:

  • Body 标签有一个生成随机的类。我正在尝试正则表达式将所有类 &lt;body class=" "&gt;&lt;body.?&gt; 匹配,但它不起作用。 $neck_pos = strpos($homepage, '&lt;body.?&gt;');
  • 我已编辑答案以跟踪 &lt;body 而不是 &lt;body&gt; 的位置。专业提示: - 使用 RegExr 测试您的正则表达式 - 检查 php documentation 以遵守预期参数
  • 感谢您的更新和建议。是否可以将regexstrpossubstr 一起使用?
  • 如果我想更改&lt;head&gt; 标签,我必须像这样使用$head = preg_replace("/https:\/\/[w]*\.*example\.com/", "https://www.example.net", $head); - 我是对的?
  • 您的大部分问题都可以在php documentation 中找到答案,您可以自己尝试。
【解决方案2】:

好吧,重申一下您在 cmets 中被告知的内容:永远不要在 HTML/XML 上使用正则表达式。始终使用解析器和(最好)xpath 进行搜索。第一步看下面的例子——你需要阅读整个主题。如果 HTML/XML 变得更复杂,搜索也会变得更复杂:

$homepage = "<head>https://www.example.com</head> <body>https://www.example.com</body>";
$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($homepage, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($doc); 
$target= $xpath->query('//body');
$target[0]->nodeValue="https://www.example.net";
echo $doc->saveHTML();

输出:

<p>https://www.example.com <body>https://www.example.net</body></p>

【讨论】:

  • 输出中的&lt;head&gt; 缺失。我正在寻找像&lt;head&gt;https://www.example.com&lt;/head&gt; &lt;body&gt;https://www.example.net&lt;/body&gt; 这样的输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 2018-09-26
  • 2012-01-03
  • 1970-01-01
相关资源
最近更新 更多