avatarAI BotBETA

PHP可以使用正则表达式匹配Markdown图片格式,核心模式为:

$pattern = '/!\[(.*?)\]\((.*?)\)/';
preg_match_all($pattern, $content, $matches);

示例解析:

$markdown = '
![logo](https://example.com/logo.png)
![avatar](/images/me.jpg "我的头像")
';

preg_match_all('/!\[(.*?)\]\((.*?)(?:\s+"(.*?)")?\)/', $markdown, $matches, PREG_SET_ORDER);

/*
结果:
array(2) {
  [0]=> array(3) {
    [0]=> "![logo](https://example.com/logo.png)"
    [1]=> "logo"
    [2]=> "https://example.com/logo.png"
  }
  [1]=> array(4) {
    [0]=> "![avatar](/images/me.jpg "我的头像")"
    [1]=> "avatar"
    [2]=> "/images/me.jpg"
    [3]=> "我的头像"
  }
}
*/

正则表达式分解:

  1. !\[ 匹配图片起始标记
  2. (.*?) 非贪婪匹配alt文字
  3. \]\( 结束alt部分
  4. (.*?) 非贪婪匹配图片路径
  5. (?:\s+"(.*?)")? 可选匹配标题(非捕获组)
  6. \) 结束图片声明

增强版(支持带空格的路径和标题):

$pattern = '/!\[(.*?)\]\((\S+?)(?:\s+(["\'])(.*?)\3)?\)/';

该模式可以匹配以下格式:

  • ![alt](path)
  • ![alt text](http://url.com/img.jpg)
  • ![alt](local.png "title")
  • ![alt](image.jpg '标题')
1 个回答

尝试一下

function extractMarkdownImages($markdown) {
    $images = [];
    
    // 匹配标准格式 ![alt](url)
    preg_match_all('/!\[(.*?)\]\((.*?)(\s+"(.*)")?\)/', $markdown, $matches);
    
    if (!empty($matches[2])) {
        foreach ($matches[2] as $index => $url) {
            $alt = $matches[1][$index] ?? '';
            $title = !empty($matches[4][$index]) ? $matches[4][$index] : '';
            
            $images[] = [
                'url' => $url,
                'alt' => $alt,
                'title' => $title
            ];
        }
    }
    
    // 匹配参考式格式
    $references = [];
    preg_match_all('/\[(.*?)\]:\s*(.*?)(\s+"(.*)")?\s*$/m', $markdown, $refMatches);
    
    if (!empty($refMatches[1])) {
        foreach ($refMatches[1] as $index => $id) {
            $references[$id] = [
                'url' => $refMatches[2][$index],
                'title' => !empty($refMatches[4][$index]) ? $refMatches[4][$index] : ''
            ];
        }
    }
    
    // 查找参考式图片引用
    preg_match_all('/!\[(.*?)\]\[(.*?)\]/', $markdown, $refImageMatches);
    
    if (!empty($refImageMatches[2])) {
        foreach ($refImageMatches[2] as $index => $id) {
            $id = empty($id) ? $refImageMatches[1][$index] : $id;
            
            if (isset($references[$id])) {
                $images[] = [
                    'url' => $references[$id]['url'],
                    'alt' => $refImageMatches[1][$index],
                    'title' => $references[$id]['title']
                ];
            }
        }
    }
    
    return $images;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题