[英]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.