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, n开发者_StackOverflow中文版ot outside of them.
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.
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. have a look here how its done and adapt: How to replace text URLs and exclude URLs in HTML tags?
精彩评论