I have the following string;
$string = '[PAGE][TITLE]Navigation Link 1[TITLE]Content Here[PAGE]';
my desired output is;
<div id="navigation Link 1">Content Here</div>
I thought I had done it with ;
$array = explode('[PAGE]', $string);
$result = $array[0];
for ($i = 1; $i < sizeof($array); $i ) {
$title = explode('[TITLE]', $array[$i]);
for ($i = 1; $i < sizeof($title); $i ) {
$result .= $i % 2 ? '<div id="' . $title[$i] . '">' . $array[$i] . '</div>' : $array[$i];
}
}
If someone could take a look at this that would be great. This has also got to work with multiple instances. For example ;
$string = '[PAGE][TITLE]Navigation Link 1[TITLE]Content Here[PAGE] some text [PAGE][TITLE]Navigation Link 2[TITLE]Content Here[PAGE]';
Thankyou for looking at this and for any help.
CodePudding user response:
You could use preg_match_all()
to get desired content :
$string = '[PAGE][TITLE]Navigation Link 1[TITLE]Content1 Here[PAGE] some text [PAGE][TITLE]Navigation Link 2[TITLE]Content2 Here[PAGE]';
$html = '';
if (preg_match_all('~\[PAGE\]\[TITLE\](.*?)\[TITLE\]([^[.]*)~',$string,$matches)) {
foreach ($matches[0] as $k => $match) {
$html .= '<div id="'.htmlentities($matches[1][$k]).'">'.htmlentities($matches[2][$k]).'</div>' . "\n";
}
}
echo $html;
output:
<div id="Navigation Link 1">Content1 Here</div>
<div id="Navigation Link 2">Content2 Here</div>