iT邦幫忙

0

[php regex]regex語法請教

舜~ 2020-11-01 11:23:381171 瀏覽

各位前輩們請教一下

我需要從html的字串中取出表格內欄位所對應的值
所以希望透過preg_match來撈資料

html的字串範本如下

<td height=23 class=xl6915090 width=157 style='height:17.25pt;width:118pt'>第一個欄位</td>
<td class=xl7115090 width=266 style='border-left:none;width:200pt'>210.61.241.108 / N/A</td>

<td height=23 class=xl6915090 width=157 style='height:17.25pt;width:118pt'>第二個欄位</td><td class=xl7115090 width=266 style='border-left:none;width:200pt'>123.123.123.123 / N/A</td>

我撈'第一個欄位',要取出 '210.61.241.108 / N/A'
我撈'第二個欄位',要取出 '123.123.123.123 / N/A'

我下的regex沒效

(?=第一個欄位\<\/td\>\<td.*?\>).*?(?<=\<\/td\>)

請問我要怎麼修正比較好?


後來改用 /第一個欄位<\/td>.*?>(.*?)<\/td>/is 來解決

function getVal(&$data, $fieldName){
    if( preg_match("/$fieldName<\\/td>.*?>(.*?)<\\/td>/is",$data, $matches) ){
        return $matches[1]; // 取出第一個括號的內容
    }
    return '';
}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2020-11-01 11:40:45
最佳解答

試試看

第一個欄位.*?>[0-9].*?<\/td>

如果是我
我會寫

[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}.*?<

可以到Regex101試試看

舜~ iT邦高手 1 級 ‧ 2020-11-01 11:54:37 檢舉

您的意思是先不要使用(?=exp) / (?:exp) 這類東東?

舜~ iT邦高手 1 級 ‧ 2020-11-01 12:31:03 檢舉

另外我舉例舉得不好...部分內容有中文

舜~ iT邦高手 1 級 ‧ 2020-11-01 12:48:24 檢舉

Regex101 !! ~~ 3Q

我要發表回答

立即登入回答