FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


preg_match





DanielXP
Hi,

I'm currently building a CMS to use for my web design.

I want to have it so I can use addons within my CMS by using code like the following to be parsed by PHP.

{addon=rss_feeds feed=events}

I want that to be the min but with options for more like,

{addon=rss_feed feed=events delay=3000 show=description box=newsbox}

Of course I want the last 4 bits to be able to go in any order.

I want to change something like,

{addon=rss_feed feed=events delay=3000 show=description box=newsbox}

into something like the following.

$rss[feed] = events
$rss[delay] = 3000
$rss[show] = description


and so on, can this be done by preg_match? I dont understand how to use the patterns to get it to work.

Any help would be great Smile

Dan
jmraker
Probably not the monstrous regex you wanted but this works based on what you have, where the options can't get more complex. It uses preg_match_all to get all the text in between every {} pair and then explodes them into arrays. Also threw in the way to replace the {} with their replacements.

Code:
$txt = 'abc{addon=rss_feed feed=events delay=3000 show=description box=newsbox}def abc{addon=rss_feed feed=events delay=1000 show=hide box=test}def';
preg_match_all('/\{(.*?)\}/', $txt, $arr, PREG_SET_ORDER);
var_dump($arr);
foreach($arr as $k1=>$v1){
   $arr2 = explode(' ', $v1[1]);
   $options = array();
   foreach($arr2 as $k2=>$v2){
      $tmp = explode('=', $v2);
      $options[$tmp[0]] = $tmp[1];
   }
   var_dump($options);
   // process options and set $replacement
   $replacement = 'REPLACE';
   $txt = str_replace($v1[0], $replacement, $txt);
}
var_dump($txt);
sonam
I don't know to do this with preg_match but I can suggest one other way. This is call your text like string and convert in rss array with keys and values
Code:

<?php
$feeds = '{addon=rss_feed feed=events delay=3000 show=description box=newsbox}';

$feed = explode(' ', $feeds);
foreach ($feed as $val){
   $vals = explode('=', $val);
   $replace = array('}', '{');
   $key = str_replace($replace, "", $vals[0]); //this will remove bracket in front
   $value = str_replace($replace, "", $vals[1]); //and the end
   $rss[$key] = $value;
}
print_r($rss);
?>


Sonam

P.S.
jmraker is faster then me. I didn't see his post because I have open your topic and first going to finish a dinner. Laughing
kacsababa
I think you can't do this with only one regex, but a regex expert could correct me.
Basicly because there is an "unlimited" number of possible parameters for an addon so you shouldn't hardcode it to multiple capturing groups, but with one repetitive group you can only access the last match I think.

Just for the sake of regex here is a preg_match_all version in a "templaty" way. Smile
Code:
<?php
$subject = '<body><h1>{addon=header}</h1><p>Not important.</p><div>{addon=coverimage feed=images show=thumbnail box=imagebox}</div><ul>{addon=rss_feed feed=events delay=3000 show=description box=newsbox}</ul><div>{addon=footer feed=footer_content show=shortfooter box=footerbox}</div></body>';

// captures the name of the addon and the body of the addon into separate groups
preg_match_all('/\{addon=(\w+)(?:(\s+?[^{}]+))*\}/i', $subject, $search, PREG_PATTERN_ORDER);

// will hold the parameters
$addons = array();

// iterate through the captured addons
for ( $iAddon = 0, $nAddons = count($search[0]); $iAddon < $nAddons; $iAddon++ ) {

  // capture the parameter name and value into separate named groups
  preg_match_all('/(?P<param>\w+)=(?P<value>\w+)/i', $search[2][$iAddon], $params, PREG_PATTERN_ORDER);

  // add an array with addon name as a key from the first search
  $addons[$search[1][$iAddon]] = array();

  // iterate through the parameters
  for ( $iParam = 0, $nParams = count($params['param']); $iParam < $nParams; $iParam++ ) {

    // add the parameter name as the key and value as value :)
    $addons[$search[1][$iAddon]][$params['param'][$iParam]] = $params['value'][$iParam];

  }

}

echo '<pre>'; print_r($addons); echo '<pre>';
DanielXP
With kacsababa's code,

Code:
preg_match_all('/(?P<param>\w+)=(?P<value>\w+)/i', $search[2][$iAddon], $params, PREG_PATTERN_ORDER);


How would i be able to get parameters in quotes like the following?

Code:
{addon=caption_image src="nil.jpeg" caption="Outside the Visitor Centre, Thames Chase Forest Centre, Upminster. Image by Malcolm Fish Photography."}


If i use it how it is no params are set, without the quote then nil and Outside are set.

Dan
Fire Boar
DanielXP wrote:
With kacsababa's code,

Code:
preg_match_all('/(?P<param>\w+)=(?P<value>\w+)/i', $search[2][$iAddon], $params, PREG_PATTERN_ORDER);


How would i be able to get parameters in quotes like the following?

Code:
{addon=caption_image src="nil.jpeg" caption="Outside the Visitor Centre, Thames Chase Forest Centre, Upminster. Image by Malcolm Fish Photography."}


If i use it how it is no params are set, without the quote then nil and Outside are set.

Dan


I guess you could change the regex to this:

Code:
/(?P<param>[A-Za-z0-9_\\-]*)\\s*=\\s*"(?P<value>(?:[^"]|\\\\")*)"/i


This only supports the quotes style, and supports quote escaping with \". Note the large number of backslashes - this has to do with what escapes:

PHP escapes \, so \\ is needed to mean a single backslash to regex. Regex also escapes \, so \\\\ are needed for a single literal \, \\ is needed for the regex escape. So \\- means "literal - character" (as opposed to a range), and \\\\" means the literal character sequence \".
DanielXP
Fire Boar wrote:
DanielXP wrote:
With kacsababa's code,

Code:
preg_match_all('/(?P<param>\w+)=(?P<value>\w+)/i', $search[2][$iAddon], $params, PREG_PATTERN_ORDER);


How would i be able to get parameters in quotes like the following?

Code:
{addon=caption_image src="nil.jpeg" caption="Outside the Visitor Centre, Thames Chase Forest Centre, Upminster. Image by Malcolm Fish Photography."}


If i use it how it is no params are set, without the quote then nil and Outside are set.

Dan


I guess you could change the regex to this:

Code:
/(?P<param>[A-Za-z0-9_\\-]*)\\s*=\\s*"(?P<value>(?:[^"]|\\\\")*)"/i


This only supports the quotes style, and supports quote escaping with \". Note the large number of backslashes - this has to do with what escapes:

PHP escapes \, so \\ is needed to mean a single backslash to regex. Regex also escapes \, so \\\\ are needed for a single literal \, \\ is needed for the regex escape. So \\- means "literal - character" (as opposed to a range), and \\\\" means the literal character sequence \".


Hi Fire Boar,

That works but then if no quotes are used it dont work. Is their a way for both ways?

Dan
Fire Boar
Allowing no-quotes is more difficult because it involves extra decisions and edge cases. For instance, how would you handle the following?

{a=b"c d=e=f g=h i j=k\"l\"m}

Intuitively, the key/value pairs might be:
a / b"c
d / e=f
g / h i
j / k"l"m (or possibly j/k\"l\"m)
jmraker
With quotes it might be easier to write or use a html tag parsing function where it takes the string addon=caption_image src="nil.jpeg" caption="Outside the Visitor Centre, Thames Chase Forest Centre, Upminster. Image by Malcolm Fish Photography."

and loops through every letter to build an array and returns
"addon"=>"caption_image"
"src"=>"nil.jpeg"
"caption"=>"Outside the Visitor Centre, Thames Chase Forest Centre, Upminster. Image by Malcolm Fish Photography."


http://kevin.deldycke.com/2007/03/ultimate-regular-expression-for-html-tag-parsing-with-php/
http://stackoverflow.com/questions/1083792/php-split-a-string-of-html-attributes-into-an-indexed-array

Another option is to use parse_ini_string function but that would require line breaks between attributes
{addon=caption_image
src="nil.jpeg"
caption="Outside the Visitor Centre, Thames Chase Forest Centre, Upminster. Image by Malcolm Fish Photography."}

where you remove the {} letters, also theres a few letters mentioned that are processed differently in some way but I guess it'll be ok if you escape them
http://us2.php.net/manual/en/function.parse-ini-string.php
Related topics
script backup database
php variables
Site Nav Suggestions...
very simple PHP code to get search query string
Executing a .sql file through PHP
HOWTO?$lang files!
Echoing Titles
PHP DB Error: syntax error
Server uptime tracker
Separators in image name on Linux/Unix servers
PHP - Find and Delete
[PHP] Server Load
PHP Preg_match() Help
preg_match multiline
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.