繁体   English   中英

特定单词的正则表达式

[英]Regular Expression for specific word

我需要从下面的字符串中找出宽度和高度

$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>';

我在下面使用找出宽度和高度,但它没有给我我想要的确切结果

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

结果是

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

应该是

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

有人对此有任何想法吗? 任何帮助将不胜感激。

提前致谢。

Umesh Kulkarni

问题是它匹配marginwidth / marginheight而不是width / height 在属性之前添加单词边界是个好主意: \\b

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

为什么要使用。*,如果你没有在风格中定义它们,宽度总是以数字形式给出。 正则表达式首先匹配marginwidth和marginheight ..你必须做这样的事情。

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

在正则表达式中给出宽度和高度之前的空间。 或使用单词边界标记\\ b而不是空格。

这可能是因为它首先匹配marginwidth =“0”marginheight =“0”。

采用:

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

你的正则表达式找到marginwidth和marginheight,因为你包括了引号。

尝试:

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

编辑:

哦,我错过了字符串末尾的显式宽度和高度属性(滚动关闭)。 我的正则表达式匹配这些:

ab0&width = 600 &height = 391 .23595

最简单的解决方案是在要匹配的单词前面加上空格(即:匹配'width'而不是'width')。

您使用的正则表达式的味道也可能支持单词边界,类似\\W表示“仅匹配非单词字符”或b表示“单词的开头”。 在这种情况下,您希望匹配“任何非单词字符后跟'宽度”,例如\\Wwidth=...\\bwidth=...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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