程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Regex pattern to match all images with replacement holding self PHP function

发布于2023-03-14 21:50     阅读(1015)     评论(0)     点赞(16)     收藏(2)


I have a preg_replace function to find all images and wrap them inside <figure> tag with different class, which depends on image source:

$pattern = '"/<img[^>]*src="([^"]+)"[^>]*alt="([^"]+)"[^>]*>\i"e';
$replacement = '"<figure class=\"" . check($1) . "\"><img src=\"$1\" alt=\"$2\" /></figure>"';
preg_replace($pattern, $replacement, $content);

Therefore, to put a right class, I wish to call a function check($source) with image source parameter. By this way, function is going to return necessary class. As you can see in a code above, I am trying to use e modifier, but it seems it doesn't work.

  1. Do I have to modify my pattern and replacement?
  2. Should I use preg_replace_all to find all the images, if they are many inside my $content variable?

解决方案


You can use preg_replace_callback() for this purpose. It allows you to define and use a function for replacement. The function should expect an array of matches and it is supposed to return the replacement value.

preg_replace() with an e modifier will also do the trick.



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/503649/1f1a11085d6179705d52/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)