正则表达式模式匹配所有图像与替换持有自我 PHP 功能
我有一个 preg_replace
函数来查找所有图像并将它们包装在具有不同类的
$pattern = '"/<img[^>]*src="([^"]+)"[^>]*alt="([^"]+)"[^>]*>\i"e';
$replacement = '"<figure class=\"" . check($1) . "\"><img src=\"$1\" alt=\"$2\" /></figure>"';
preg_replace($pattern, $replacement, $content);
因此,要放置正确的类,我希望使用图像源参数调用函数 check($source)
。这样,函数就会返回必要的类。 正如您在上面的代码中看到的,我正在尝试使用 e 修饰符,但似乎不起作用。
- 我是否必须修改我的模式和替换?
- 如果我的
$content
变量中有很多图像,我是否应该使用preg_replace_all
查找所有图像?
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.
- Do I have to modify my pattern and replacement?
- Should I use
preg_replace_all
to find all the images, if they are many inside my$content
variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
preg_replace_callback()
为此目的。它允许您定义和使用函数进行替换。该函数应该期望一个匹配数组,并且应该返回替换值。preg_replace()
带有e
修饰符也能达到目的。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 ane
modifier will also do the trick.检查正则表达式库,已经有一些HTML图像模式。
Check the regular expression library, there are already some HTML image patterns.