我不明白為什麼這段程式碼沒有將標題變成正確的鏈接
P粉715228019
P粉715228019 2023-09-11 23:44:46
0
1
510

我的資料庫中有以下字串:

"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>";
    }

我期望「標題」變數為 ,但結果是

全部回覆(1)
P粉776412597

基於@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>";
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!