Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for specific word

Tags:

regex

php

I need to find out the width & height from the below string

$embed_code = '<iframe id="streamlike_player" name="streamlike_player" marginwidth="0" marginheight="0" src="http://cdn.streamlike.com/hosting/orange-business/embedPlayer.php?med_id=5bad83b03860eab0&width=600&height=391.235955056&lng=fr" frameborder="0" width="600" scrolling="no" height="391"></iframe>';

I am using below to find out width & height but its not giving me exact result I want

preg_match("/width=\"(.*?)\"/", $embed_code, $w_matches);
preg_match("/height=\"(.*?)\"/", $embed_code, $h_matches);

The result is

Array
(
    [0] => width="0"
    [1] => 0
)
Array
(
    [0] => height="0"
    [1] => 0
)

which should be

Array
(
    [0] => width="600"
    [1] => 600
)
Array
(
    [0] => height="391"
    [1] => 391
)

Any one have any idea regarding it? Any help will be appreciated.

Thanks in advance.

Umesh Kulkarni

like image 497
Umesh Kulkarni Avatar asked Aug 20 '26 19:08

Umesh Kulkarni


2 Answers

why to use .*, width are always given as digits if you are not defining them in style. also the regex is matching marginwidth and marginheight first.. you have to do something like this.

preg_match("/ width=\"(\d+)\"/", $embed_code, $w_matches);
preg_match("/ height=\"(\d+)\"/", $embed_code, $h_matches);

give space before width and height in regex. or use word boundary tag \b instead of space.

like image 178
Aamir Rind Avatar answered Aug 23 '26 08:08

Aamir Rind


The problem is that it matches marginwidth / marginheight instead of width / height. It would be a good idea to add a word boundary before the attributes: \b

preg_match("/\bwidth=\"(.*?)\"/", $embed_code, $w_matches);
preg_match("/\bheight=\"(.*?)\"/", $embed_code, $h_matches);
like image 34
Karolis Avatar answered Aug 23 '26 10:08

Karolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!