简体   繁体   中英

Regular Expression for specific word

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

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);

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.

Its probably because it matches the marginwidth="0" marginheight="0" first.

use:

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

Your regex finds marginwidth and marginheight cause you included the quotation marks.

Try:

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

EDIT:

Oha, I missed the explicit width and height attributes at the end of your string (scrolled off). My regexes match these:

ab0&width= 600 &height= 391 .23595

The dead simplest solution is to include the space in front of the word you want to match (ie: match in ' width' rather than 'width').

The flavor of regular expression you use may also support word boundaries, something like \\W which means "match only a non-word character" or b which means "beginning of a word". In this case you want to match "any non-word character followed by 'width", for example \\Wwidth=... or \\bwidth=...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM