Regular Expression To Get Text From Css
Solution 1:
If you have CSS styles isolated in a javascript string, you can get the width value with this regex:
var re = /\.body\s*\{[^\}]*?width\s*:\s*(.*);/m;
var matches = str.match(re);
if (matches) {
var width = matches[1];
}
Test case here: http://jsfiddle.net/jfriend00/jSDeJ/.
The height value can be obtained with this regex:
\.body\s*\{[^\}]*?height\s*:\s*(.*);/m;
If you just want the text (whatever it is that's inside the curly brackets for the body tag, then you can do that with this:
var re = /\.body\s*\{([^\}]*?)\}/m;
var matches = str.match(re);
if (matches) {
var width = matches[1];
}
You can see it work here: http://jsfiddle.net/jfriend00/jSDeJ/3/
If you then want to replace the entire .body style with your own string, you can do that like this:
var str = " <style>\n.body{\n width:2px; \n height:3px; \n } \n</style>";
var re = /(\.body\s*\{)([^\}]*?)(\})/m;
var newStyle = "width: 20px; \nheight: 1000px;";
var result = str.replace(re, "$1" + newStyle + "$3");
alert(result);
You can see that work here: http://jsfiddle.net/jfriend00/jSDeJ/8/
Solution 2:
This looks promising...
https://github.com/sabberworm/PHP-CSS-Parser
Or, if you just want to know the "computed value", I'd rely on the browser's parser and just extract the values with javascript DOM methods.
Hope that helps...
Post a Comment for "Regular Expression To Get Text From Css"