我不明白为什么这段代码没有将标题变成正确的链接
P粉715228019
P粉715228019 2023-09-11 23:44:46
0
1
546

我的数据库中有以下字符串:

"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学习者快速成长!