我的数据库中有以下字符串:
"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粉715228019457 天前577
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>"; }