换入<a> tags specific characters in HTML tables with regex &amp; PHP</a>

时间:2010-12-10 22:07:21

标签: php regex preg-replace

我有一个文本......在其中我有段落和表格...我需要替换每个X(一个日本汉字字符准确......但它可以是任何字符)具有<a href="http://example.com/#X">X</a>的表格,但只包含表格中的X,而不是表格中的那些。

单个表中可能有多个X,因此preg_replace('#<td>(X)#','replacewith',$source)无效,因为它只替换了其中一个。

有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:0)

$startIndex = strpos($source, '<table');

while ($startIndex !== false) {
    $endIndex = strpos($source, '</table>', $startIndex);

    $excerpt = substr($source, $startIndex, $endIndex - $startIndex);
    $excerpt = preg_replace('/(X|Y|Z)/', '<a href="http://example.com/#$1">$1</a>', $excerpt);
    $source = substr_replace($source, $excerpt, $startIndex, $endIndex - $startIndex);

    if (strlen($source) < $endIndex)
        $startIndex = false;
    else
        $startIndex = strpos($source, '<table', $endIndex);
}

修改:修复,测试,无效。

答案 1 :(得分:0)

用正则表达式解析html真的不太漂亮。 看看它是如何完成和改编的:How to replace text URLs and exclude URLs in HTML tags?