views:

295

answers:

2

I'm curious how, in ActionScript 3, to parse the font attributes of an HTML formatted content string. Lets take the following example content string:

var content:String = '<font face="Archer-Bold" size="12" color="#000000">My Content</font>';

I'd like to parse that string and create an object with the font attributes in it. So a resulting object would trace the following:

trace( fontInfo.name ); // output: "Archer-Bold"
trace( fontInfo.size ); // output: "12"
trace( fontInfo.color ); // output: "#000000"

I'm guessing regular expressions is the way to go, but I know nothing about them. Thoughts?

A: 

How about using an xml object? For example:

var fontnode:XML = new XML(content);
trace(fontnode.@face);
trace(fontnode.@size);
trace(fontnode.@color);
mweiss
This method will fail if the content contains some invalid markup, i.e. "My <br> content"
radekg
A: 

Hi, This is what I came up with. It is ideal job for regular expressions:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
 creationComplete="onComplete();">

 <mx:Script>
  <![CDATA[
   import mx.controls.Alert;
   import mx.utils.ObjectUtil;
   private var targets:Array = new Array();
   private function onComplete():void {

    var face:String = null;
    var size:String = null;
    var color:String = null;

    var content:String = '<font face="Archer-Bold" size="12" color="#000000">My <br> Content</font>';

    // since the content has invalid XML <br> tag XML construction will fail:
    //var x:XML = new XML(content);

    var faces:Array = content.match(/face\s*=\s*["'](.[^"']*)["']/);
    // array is null if no matches found:
    if ( faces != null ) {
     face = faces[1];
    }

    var sizes:Array = content.match(/size\s*=\s*["'](\d{1,})["']/);
    // array is null if no matches found:
    if ( sizes != null ) {
     size = sizes[1];
    }

    var colors:Array = content.match(/color\s*=\s*["'](.[^"']*)["']/);
    // array is null if no matches found:
    if ( colors != null ) {
     color = colors[1];
    }

    Alert.show("Font : " + face + ", " + size + ", " + color + "." );
   }
  ]]>
 </mx:Script>

</mx:WindowedApplication>

Hope that helps.

radekg