Reputation:
HI
I have an application where users can paste their embed code.While displaying I want to change the height and width of the embed code to a fixed value of my choice. Can you tell me the regular expression to find the width and height in the embed code. width="300" height="500". I want to be able to get these two values completely so that I can replace them.
Thanks
Upvotes: 1
Views: 4095
Reputation: 64929
Regexes are fundamentally bad at parsing HTML (see Can you provide some examples of why it is hard to parse XML and HTML with a regex? for why). What you need is an HTML parser. See Can you provide an example of parsing HTML with your favorite parser? for examples using a variety of parsers.
You may be interested into the two answers related to JavaScript: jQuery and DOM.
Upvotes: 1
Reputation: 9265
The following examples take into account the ordering, what quotations are used, and if people put in spaces
A straight replace:
embeddedString = embeddedString.replace(/(width\s*=\s*["'])[0-9]+(["'])/ig, $1 + yourWidth + $2);
embeddedString = embeddedString.replace(/(height\s*=\s*["'])[0-9]+(["'])/ig, $1 + yourHeight + $2);
Or to transform the width:
embeddedString = embeddedString.replace(/width\s*=\s*["']["']/ig, function($0, $1)
{
return $1 * 2;
});
if you actually want to remove the whole thing, but use the values:
var originalWidth;
var originalHeight;
embeddedString = embeddedString.replace(/(?:width|height)\s*=\s*["']([0-9]+)["']\s*(?:width|height)\s*=\s*["']([0-9]+)["']/ig, function($0, $1, $2, $3, $4)
{
// $0 = original string
// $1 = either 'width' or 'height'
// $2 = the value of width or height, depending on above
// $3 = either 'width' or 'height'
// $4 = the value of width or height, depending on above
// here you might want to set another value, eg:
originalWidth = $2;
return "";
});
Upvotes: 1
Reputation: 113767
This one does it:
width="(.*?)" height="(.*?)"
and grab the first and second values. What language are you using? The implementation might be different.
In PHP:
$pattern = '/width="(.*?)" height="(.*?)"/';
$subject = 'width="500" height="300"';
preg_match($pattern, $subject, $matches);
print_r($matches);
Upvotes: 0