搜索PHP字符串,然后匹配并替换SPAN标记的所有实例

时间:2017-07-26 16:45:33

标签: php preg-replace

我正在围成一圈。我想在字符串中搜索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>';

1 个答案:

答案 0 :(得分: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>';