提问人:Ben 提问时间:7/27/2017 最后编辑:Ben 更新时间:8/2/2017 访问量:315
搜索PHP字符串,然后匹配并替换SPAN标签的所有实例
Search PHP string, then match and replace all instances of SPAN tag
问:
我兜圈子。我想在字符串中搜索 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>';
答:
0赞
Ben
8/2/2017
#1
好吧,认为我已经得到了它,任何人都可以改进它吗?谢谢
// 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> '.$tip.'</li>';
}
echo '<ul>';
上一个:数组内的 Foreach 循环
评论