【问题标题】:HTML Parsing - Convert a Text into a Link [closed]HTML 解析 - 将文本转换为链接 [关闭]
【发布时间】:2013-03-19 17:34:57
【问题描述】:

假设我有这个文本:

亚伦与他兄弟在米利巴的罪行有关(民数记 20:8-13),因此不被允许进入应许之地。当部落到达何珥山时,“在以东地的边缘”,摩西在上帝的命令下带领亚伦和他的儿子以利亚撒到了山顶,在所有人的视线中。他在那里脱下亚伦的祭司袍,给以利亚撒穿上;亚伦死在山顶上,享年 123 岁(民数记 20:23-29。比较 申命记 10:632 :50)

我想要做的是,将上面的每一个粗体文本都转换成一个链接,如果是链接的话:

这段文字的结构如下:

<DIV>
  <B>Aaron</B>
  <SPAN>
    Aaron was implicated in the sin of his brother at Meribah (Num. 20:8-13), and on that account was not permitted to enter the Promised Land. When the tribes arrived at Mount Hor, "in the edge of the land of Edom," at the command of God Moses led Aaron and his son Eleazar to the top of that mountain, in the sight of all the people. There he stripped Aaron of his priestly vestments, and put them upon Eleazar; and there Aaron died on the top of the mount, being 123 years old (Num. 20:23-29. Comp. Deut. 10:6; 32:50)
  </SPAN>
</DIV>

任何伟大的想法将不胜感激。谢谢:)


编辑

代码:

$chapters = array ("Deut", "Num");

$html = file_get_html($link);

foreach($html->find('div') as $dict) {
    $descr  = $dict->find('SPAN', 0)->innertext;    
    $descrl = preg_replace("/$chapters\. [0-9:-]*/", "<a href=\"$0\">$0</a>", $descr); //--> See description below

    echo $descrl . "<hr/>";
}

说明:虽然我将$chapters 更改为NumDeut 之类的单个单词,但效果很好,但是当我将其更改为$chapters 时,它不会返回任何链接。

【问题讨论】:

  • 这个问题没有显示任何研究工作。 做好功课很重要。告诉我们您发现了什么以及为什么它不能满足您的需求。这表明您已经花时间尝试帮助自己,它使我们免于重复明显的答案,最重要的是它可以帮助您获得更具体和相关的答案。 FAQ.
  • 试试正则表达式。提取所需的字符串,并将其替换为您想要的。对于您的第一个示例,即。编号。 20:8-13,尝试 /num\。 [0-9:-]*/,这在您的上下文中足够精确。
  • 你可以使用 javascript,因为这是你修改 HTML 页面的 DOM 的方式吗?
  • @zoujyjs:谢谢,我会尽快更新代码..
  • @Markasoftware:是的,当然……

标签: php javascript html parsing dom


【解决方案1】:

您没有指定规则,您应该自己定义和改进;我已经处理了你的具体情况。

//replace against either book followed by period followed by space
//followed by one or more digit, comma, semicolon, space, or dash
txt.replace(/(Num|Deut)\. ([\d:,; -]+)/g, function (match, book, verses) {
    var link = '';
    //split the verse on semicolon + space as each must be linked
    verses.split(/;\s+/).forEach(function (elem) {
        //create the link; replace : with period
        link += '<a href="' + book.toLowerCase() + elem.replace(':', '.') + '">'
            + book + '. ' + elem + '</a> ';
    });
    return link;
});

http://jsfiddle.net/XaVXW/

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 2011-03-09
    • 1970-01-01
    • 2022-01-20
    • 2014-01-17
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2013-07-27
    相关资源
    最近更新 更多