Regex pattern to match all images with replacement holding self PHP function
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 m开发者_运维技巧y pattern and replacement?
- 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.
Check the regular expression library, there are already some HTML image patterns.
精彩评论