我的資料庫中有以下字串:
"Minecraft is a sandbox video game developed by Mojang Studios from Sweden. Its concept revolve around procedurally generated world made of cubic blocks. Minecraft is the best-selling game in history, having over 238 millions of copies sold. <h1>Gameplay</h1> Minecraft is played from first-person perspective. Gameplay includes mining, crafting, combat, building and terraforming. Usually when a new single-player game is started, a player is placed into a procedurally generated world. The player can encounter various "mobs"...
我正在嘗試從字串中提取標題值,並使用以下程式碼將其轉換為連結
$heading=''; $match1=array(); $matched=preg_match("/<h\d>/",$part,$match1,PREG_OFFSET_CAPTURE); if($matched) { $match2=array(); preg_match("#</h\d>#",$part,$match2,PREG_OFFSET_CAPTURE); $heading= substr($part,$match1[0][1]+4,$match2[0][1]); $heading="<a href='$heading'>$heading</a>"; }
我期望「標題」變數為 ,但結果是
P粉715228019458 天前583
P粉7764125972023-09-12 18:15:37
基於@theforthbird 的評論- 您可以使用單一正則表達式捕獲您想要的字串,儘管通常使用正則表達式解析HTML 會導致一個痛苦的世界,所以雖然這可能適合您當前的目的,但如果您需要沿著這些路線做更多的事情,最好將HTML 解析為DOM 並提取您需要的內容。
$heading = ''; preg_match('/<h(\d)>(.*?)<\/h>/', $string, $matches); // print_r($matches); # uncomment this to see everything that was 'matched' by this regex if (!empty($matches[2])) { $heading = "<a href='{$matches[2]}'></a>"; }