2017-07-26 16 views
0

我正在圈圈。我想为一个span标签搜索一个字符串,然后用一个替代版本替换它,最后打印所有更改的列表。搜索PHP字符串,然后匹配并替换SPAN标记的所有实例

我希望这有助于向某人展示我正在尝试做什么......看上了挑战吗?

// create array to hold tooltips 
$tips = array(); 

// search $content string and add all matching strings to $tips array 
$haystack = $content; 
$needle = '<span class="has-tip">['.ADD THIS TO $tips ARRAY.']</span>'; 

// print $content and string replace as such... 
$replace = '<span class="has-tip">['.$tips[$i].']</span>'; 
$with = '<a href="#_ftn'.$i.'" name="_ftnref'.$i.'"><span data-tooltip aria-haspopup="true" class="has-tip top" data-disable-hover="false" tabindex="'.$i.'" title="'.$tips[$i].'">['.$i.']</span></a>'; 

print $content; 

// list all tooltips 
echo '<ul>'; 
foreach ($tips as $key => $tip) { 
    echo '<li><a href="#_ftnref'.$key.'" name="_ftn'.$key.'">['.$key.']</a> '.$tip.'</li>'; 
} 
echo '<ul>'; 
+2

也许如果你能告诉我们数据 - 原始输入和期望的输出 - 我们可以帮助代码。 –

+0

谢谢雷... http://4ipcouncil.com/footnotes.html – Ben

+0

请帮忙吗? – Ben

回答

0

好吧,想想我明白了,任何人都可以改善这一点吗?谢谢

// create array to hold tooltips 
$tips = array(); 

$dom = new DOMDocument; 
$dom->loadHTML($content); 
foreach ($dom->getElementsByTagName('span') as $tag) { 
    if ($tag->className = 'has-tip') { 
    $tips[] .= $tag->nodeValue; 
    } 
} 

$footnoted = $content; 

foreach ($tips as $key => $tip){ 
    $i = $key + 1; 
    $footnoted = str_replace('<span class="has-tip">'.$tip.'</span>', '<a href="#_ftn'.$i.'" name="_ftnref'.$i.'"><span data-tooltip aria-haspopup="true" class="has-tip top" data-disable-hover="false" tabindex="'.$i.'" title="'.$tip.'">['.$i.']</span></a>', $footnoted); 
} 

print $footnoted; 

// list all tooltips 
echo '<ul class="footnotes">'; 
foreach ($tips as $key => $tip) { 
    $t = $key + 1; 
    echo '<li><a href="#_ftnref'.$t.'" name="_ftn'.$t.'">['.$t.']</a>&nbsp;'.$tip.'</li>'; 
} 
echo '<ul>'; 
相关问题