Want to improve this question? Update the question so it foc开发者_Python百科uses on one problem only by editing this post.
Closed 8 years ago.
Improve this questioni have a string for example
$str = "[H]Test[/H] My test string [H]Test2[/H] My second Test string";
and i want to make a list inside "[H]" and make them click able like
<a href="#faq-1">Test</a>
<a href="#faq-2">Test2</a>
and and also want to include this
<a name="faq-1"></a>Test
<a name="faq-2"></a>Test2
in $str
any help please
Here's what I came up with.
<?php
$str = "[H]Test[/H] My test string [H]Test2[/H] My second Test string";
/**
* Helper class
*/
class FaqHelper {
static $count = 1;
static $listItems = array();
static $prefix = 'faq-';
static function GetList() {
$items = '';
foreach (self::$listItems as $id => $label) {
$items .= '<li><a href="#' . self::$prefix . $id .'">' . $label . '</a></li>';
}
return '<ul>'. $items .'</ul>';
}
static function ReplaceCallback($matches)
{
$id = self::$count;
$label = $matches[1];
self::$listItems[$id] = $label;
$res = '<span id="'. self::$prefix . $id .'">' . $label . '</span>';
self::$count++;
return $res;
}
}
$text = preg_replace_callback(
"#\[H\]([^\[]+)\[/H\]#",
array('FaqHelper', "ReplaceCallback"),
$str
);
$list = FaqHelper::GetList();
echo $list;
echo '<br /><br />';
echo $text;
?>
精彩评论