Heim > Fragen und Antworten > Hauptteil
Ich habe die folgende Zeichenfolge in meiner Datenbank:
"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"...
Ich versuche, den Titelwert aus einer Zeichenfolge zu extrahieren und ihn mit dem folgenden Code in einen Link umzuwandeln
$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>"; }
Ich habe erwartet, dass die Variable „title“ ,但结果是
P粉715228019457 Tage vor576
P粉7764125972023-09-12 18:15:37
基于 @theforthbird 的评论 - 您可以使用单个正则表达式捕获您想要的字符串,尽管通常使用正则表达式解析 HTML 会导致一个痛苦的世界,所以虽然这可能适合您当前的目的,但如果您需要沿着这些路线做更多的事情,你最好将 HTML 解析为 DOM 并提取你需要的内容。
$heading = ''; preg_match('/<h(\d)>(.*?)<\/h\1>/', $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>"; }