Umesh Kulkarni
Umesh Kulkarni

Reputation: 41

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

Upvotes: 2

Views: 3587

Answers (5)

Aamir Rind
Aamir Rind

Reputation: 39709

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.

Upvotes: 3

Bryan Oakley
Bryan Oakley

Reputation: 386372

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=...

Upvotes: 0

Karolis
Karolis

Reputation: 9582

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

Upvotes: 3

Felix Glas
Felix Glas

Reputation: 15524

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

Upvotes: 2

Kaken Bok
Kaken Bok

Reputation: 3395

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

Upvotes: 1

Related Questions