2013-03-29 134 views
0

假设我有这样的文字:HTML解析 - 转换文本到链接

阿龙在他的弟弟在米利巴罪牵连:和上(民20 8-13)。该帐户不得进入应许之地。当部落抵达何尔山时,“在以东地的边缘”,在摩西的命令下,摩西带领亚伦和他的儿子以利亚撒到达山顶,在所有的人面前。在那里,他剥夺亚伦祭司的衣服,放在以利亚撒身上;和亚伦死在那里上安装的顶部,是123年岁(民20:23-29比较申10:。。6; 32:50

我想要做的是,每一个大胆的文本转换入一个链接,和纽带,如果它是:

  • 民。 20:8-12,应该像:< a href =“num20.8-12”> Num。 20:8-13 </a>
  • Deut。 10:6; 32:50,应该是这样的:Deut。 10:6 </a> < a href =“deut32.50”> Deut。 32:50 </A>

本文的结构是象下面这样:

<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,它不返回任何链接。

+2

这个问题并没有表现出任何的研究工作。 **做你的作业很重要**。告诉我们你发现了什么,***为什么它不符合你的需求。这表明你已经花时间去尝试帮助你自己了,它使我们避免重申明显的答案,最重要的是它可以帮助你得到更具体和相关的答案。 [FAQ](http://stackoverflow.com/questions/how-to-ask)。 –

+2

尝试正则表达式。提取所需的字符串,并将其替换为所需的字符串。对于你的第一个例子,即。民。 20:8-13,try/num \。 [0-9: - ] * /,在您的上下文中足够精确。 – zoujyjs

+0

您是否可以使用javascript,因为这是您修改HTML页面的DOM的方式? – Markasoftware

回答

2

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

//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/