Regex to change height and width value in embed code

HI

I have an application where users can paste their embed code. While showing, I want to change the height and width of the embed code to a fixed value of my choice. Can you tell me a regex 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

+1


a source to share


3 answers


The following examples consider the order, what quotes are used, and if people put spaces

Direct replacement:

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 convert the width:



embeddedString = embeddedString.replace(/width\s*=\s*["']["']/ig, function($0, $1)
{
    return $1 * 2;
});

      

if you really want to remove the whole thing, but use 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 "";
});

      

+1


a source


Regexes are fundamentally bad at parsing HTML (see Can you give some examples of why it is difficult to parse XML and HTML with regex? For what). You need an HTML parser. See Can you give an example of parsing HTML with your favorite parser? for examples using various parsers.



You may be interested in two JavaScript related answers: jQuery and DOM .

+1


a source


This does it:

width="(.*?)" height="(.*?)"

      

and take the first and second values. What language do you use? Implementation may vary.

In PHP:


     $pattern = '/width="(.*?)" height="(.*?)"/';
     $subject = 'width="500" height="300"';

     preg_match($pattern, $subject, $matches);

     print_r($matches);


      

0


a source







All Articles