2016年11月14日 星期一

【PHP】把 table 的寬變成空白,preg_replace取代某部分

本來覺得很簡單的問題,結果試了好久,這邊紀錄一下,
今天有一段字串,
例如:<table class="mytable" width="200" height="300">
目的把是把 width="" 變成:
<table class="mytable" width="" height="300">
作法:
$str = '<table class="mytable" width="200" height="300">';  
echo preg_replace('/(<table.*?width=")(.*?)(".*?>)/i', '$1$3', $str);

原理:
preg_replace 的第一部分包含了三組的括號(),
與第二部分的$1$3做對應,因為跳過了$2所以第二組的括號()就會被取代成空白,
$0 的話代表搜尋本身,可以做更多的應用

沒有留言:

張貼留言