PHP替换文本并检测对应文件存在性的技术实现需求
解决方案
直接用preg_replace_callback就能搞定,它允许你在替换过程中加入自定义逻辑,正好满足检测文件、插入内容的需求,比单纯用preg_replace灵活得多。
处理IIxxxII标识的代码
$text = preg_replace_callback('/II(.*?)II/', function($matches) { $filename = $matches[1]; // 生成图片标签,修正你原代码里的`scr`拼写错误(应为`src`) $imgTag = "<img src='img/{$filename}'>"; // 拼接对应的txt文件路径 $txtPath = "img/" . pathinfo($filename, PATHINFO_FILENAME) . ".txt"; // 检测文件存在则调用函数追加内容 if (file_exists($txtPath)) { $imgTag .= "<div class='img-desc'>" . image_text_print($txtPath) . "</div>"; } return $imgTag; }, $text);
处理你原本需要的<img>xxx<img>标识的代码
如果想换回最初的<img>xxx<img>标记,只需要修改正则表达式即可:
$text = preg_replace_callback('|<img>(.*?)<img>|', function($matches) { $filename = $matches[1]; $imgTag = "<img src='img/{$filename}'>"; $txtPath = "img/" . pathinfo($filename, PATHINFO_FILENAME) . ".txt"; if (file_exists($txtPath)) { $imgTag .= "<div class='img-desc'>" . image_text_print($txtPath) . "</div>"; } return $imgTag; }, $text);
关键说明
preg_replace_callback的匿名函数会在每次匹配到内容时执行,你可以在里面完成文件检测、函数调用等所有额外操作。pathinfo($filename, PATHINFO_FILENAME)用来提取不带后缀的文件名(比如从30.jpg拿到30),避免因文件名带后缀导致找不到对应的.txt文件。
内容的提问来源于stack exchange,提问作者Jorgensen
相关产品推荐
相关产品推荐

