php - 如何解析一些html标签内容并用一些特殊字符(如 "|")分隔它们?

标签 php html-parsing

我有一个变量,例如:

$content = '
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/digital_marketing">digital marketing</a>
</i>
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/seo">seo</a>
</i>
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/internet_marketing">internet marketing</a>
</i>';

如何提取这样的标签内容: 数字营销|搜索引擎优化|互联网营销

谢谢。

最佳答案

您尝试访问的所有内容都存在于 a 标记中,该标记只是 i 的子标记。在这里,我使用 DOMDocument 来实现所需的结果。

Try this code snippet here

<?php

ini_set('display_errors', 1);
$string=<<<HTML
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/digital_marketing">digital marketing</a>
</i>
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/seo">seo</a>
</i>
<i class="fa fa-hashtag" aria-hidden="true">
    <a href="http://example.com/tag/internet_marketing">internet marketing</a>
</i> 
HTML;
$domDocument = new DOMDocument();
$domDocument->loadHTML($string);

$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query("//i/a");
foreach($results as $result)
{
    $data[]= $result->textContent;
}
echo implode("|",$data);

关于php - 如何解析一些html标签内容并用一些特殊字符(如 "|")分隔它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44680027/

相关文章:

PowerShell - HTML 解析 : get information from a website

perl - 将 html 嵌套列表解析为 perl 数组

Javascript:涉及数学运算符时的 parseInt 问题

java - 使用 JTidy 从 html 中删除所需的标签

c# - 获取网页中所有 url 的列表

php - 如何在 Symfony2 中压缩 html 输出?

php - 使用 SQL 将 2 个结果合并为 1 个

php正则表达式按[%%%]分割字符串

javascript - jquery ajax unhide div 如果变量等于

php - Magento 迁移中断 - 子页面返回 404