I'm using a content management system and would like to give users the ability to insert snippets/variables that could then be processed by the php and load specific content into the space.
An example would be something like:
[[gallery:landscapes]]
The user would insert that into the WYSIWYG then when the page was processed I would like it to identify the two components
1.) The 'gallery' variable
2.) The 'landscapes' variable (so the 'landscapes' gallery could be inserted into the page)
I'm assuming regex is the way to go on this but I can't seem to find a good way to get this working.
Custom inline variables
Moderator: General Moderators
Re: Custom inline variables
Given the data of:
[text]dsfg dfg [[gallery:landscapes]] sfgfdgsdfg [[test:user]] dfasdfsdf[/text]
this bit of code (the above is in $subject)
will give you the following array for $aryMatch:
[text]array(3) {
[0]=>
array(2) {
[0]=>
string(22) "[[gallery:landscapes]]"
[1]=>
string(13) "[[test:user]]"
}
[1]=>
array(2) {
[0]=>
string(7) "gallery"
[1]=>
string(4) "test"
}
[2]=>
array(2) {
[0]=>
string(10) "landscapes"
[1]=>
string(4) "user"
}
}[/text]
So you can then add the following code to handle these matches:
Now the original $subject will have those insert keys replaces with their output.
Note: Some editors if they enter the key on a blank line will wrap it with a <p> </p> set, You may want to check for that as well (ie, do two str_replace, the second one with '<p>'.$search.'</p>'
-Greg
[text]dsfg dfg [[gallery:landscapes]] sfgfdgsdfg [[test:user]] dfasdfsdf[/text]
this bit of code (the above is in $subject)
Code: Select all
preg_match_all('/\[\[(.+?):(.+?)\]\]/', $subject, $aryMatch, PREG_PATTERN_ORDER);[text]array(3) {
[0]=>
array(2) {
[0]=>
string(22) "[[gallery:landscapes]]"
[1]=>
string(13) "[[test:user]]"
}
[1]=>
array(2) {
[0]=>
string(7) "gallery"
[1]=>
string(4) "test"
}
[2]=>
array(2) {
[0]=>
string(10) "landscapes"
[1]=>
string(4) "user"
}
}[/text]
So you can then add the following code to handle these matches:
Code: Select all
if (count($aryMatch[1])>0) {
$aryInsert = array();
foreach($aryMatch[1] as $key=>$val) {
if (!array_key_exists($aryMatch[0][$key],$aryInsert)) { // don't reprocess a combination already handled
$curKey = $aryMatch[2][$key];
switch($val) {
case 'gallery':
// DO CODE HERE TO GENERATE GALLERY. THE PASSED ID WILL BE $curKey
$strOutput = "<p>There will be a gallery of ".$curKey." going here.</p>";
break;
case 'test':
// DO CODE HERE TO GENERATE TEST. THE PASSED ID WILL BE $curKey
$strOutput = "<p>Here we will test ".$curKey.".</p>";
break;
default:
$strOutput = '';
}
$aryInsert[$aryMatch[0][$key]] = $strOutput;
}
}
foreach($aryInsert as $search=>$replace) {
$subject = str_replace($search,$replace,$subject);
}
}Note: Some editors if they enter the key on a blank line will wrap it with a <p> </p> set, You may want to check for that as well (ie, do two str_replace, the second one with '<p>'.$search.'</p>'
-Greg