PHP DOM 解析器:查找所有链接的文本并更改它
我是 PHO DOM 解析器的新手。我有一个像这样的字符串:
$coded_string = "Hello, my name is <a href="link1">Marco</a> and I'd like to <strong>change</strong> all <a href="link2">links</a> with a custom text";
并且我想使用自定义字符串更改链接中的所有文本(在示例中,Marco 和链接),比如 < em>你好。
我怎样才能在 PHP 上做到这一点?目前我只将 XDOM/XPATH 解析器初始化为:
$dom_document = new DOMDocument();
$dom_document->loadHTML($coded_string);
$dom_xpath = new DOMXpath($dom_document);
I'm new into PHO DOM Parser. I have a string like this :
$coded_string = "Hello, my name is <a href="link1">Marco</a> and I'd like to <strong>change</strong> all <a href="link2">links</a> with a custom text";
and I'd like to change all text in the links (in the example, Marco and links) with a custom string, let say hello.
How can I do it on PHP? At the moment I only initilized the XDOM/XPATH parser as :
$dom_document = new DOMDocument();
$dom_document->loadHTML($coded_string);
$dom_xpath = new DOMXpath($dom_document);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您对 xpath 在这里有很好的了解,下面的示例展示了如何选择所有 textnode 子节点 (
DOMText
Docs) 的元素并更改其文本:
让我知道这是否有帮助。
You have a good sense for xpath here, the following example shows how to select all textnode children (
DOMText
Docs) of the<a>
elements and change their text:Let me know if this is helpful.
尝试 phpQuery ( http://code.google.com/p/phpquery/ ):
打印:
Try phpQuery ( http://code.google.com/p/phpquery/ ):
Prints: