简体   繁体   English

<a>使用正则表达式和PHP将HTML表格</a>中的<a>标签特定字符</a>包装起来

[英]Wrap in <a> tags specific characters in HTML tables with regex & PHP

I have a text... and in it I have paragraphs and tables... I need to replace every X (a single Japanese kanji character to be precise... but it could be any character) which is in one of the tables with <a href="http://example.com/#X">X</a> , but only those X that are in the tables, not outside of them. 我有一个文本...并且其中有段落和表格...我需要替换其中一个表格中的每个X(准确地说是单个日文汉字字符...但可以是任何字符)与<a href="http://example.com/#X">X</a> ,但只能使用表中的X,而不能在表外。

There can be several X in a single table so preg_replace('#<td>(X)#','replacewith',$source) wouldn't work as it replaces only one of the X. 一个表中可以有多个X,因此preg_replace('#<td>(X)#','replacewith',$source)将不起作用,因为它仅替换了X中的一个。

Any ideas? 有任何想法吗? Thanks. 谢谢。

$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);
}

Edit : fixed, tested, works. 编辑 :修复,测试,运行。

parsing html with regex is really not pretty. 用正则表达式解析html确实不是很漂亮。 have a look here how its done and adapt: How to replace text URLs and exclude URLs in HTML tags? 在这里看看它是如何完成和适应的: 如何替换文本URL和排除HTML标签中的URL?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM