Reputation: 5946
I am shifting an image tag from one place to another. It currently takes 2 regular expressions, one to find the image tag and one to replace it. Can this be done with one regular expression?
<?php
// Always shorttag
$thumbnail_match_result = preg_match('{<\s*img.*?/>}', $thumbnail, $matches);
$thumbnail_tag = array_shift($matches);
$thumbnail_caption = preg_replace('{<\s*img.*?/>}',"", $thumbnail);
?>
<h4><?php print $title ?></h4>
<a title="<?php print $title ?>" href="<?php print $original_image ?>" data-gallery="">
<?php print $thumbnail_tag ?>
</a>
<?php print $thumbnail_caption; ?>
Thumbnail looks like:
<img typeof="foaf:Image" class="img-responsive" src="/files/styles/photocomp_large/public/lovejoymask400mm_0.jpg?itok=pqICHn8s" width="960" height="656" alt="aly" title="title" /> <blockquote class="image-field-caption">test</blockquote>
Upvotes: 0
Views: 47
Reputation: 351228
You could use two capture groups, one for each part (image tag, text), like this:
preg_match('{(<\s*img.*?/>)(.*)}', $thumbnail, $matches);
Then $matches
will contain the complete matched string in index 0, which you don't need, but in index 1 and 2 you will find the captured groups:
print $matches[1]; // <img ... />
print $matches[2]; // <blocknote>text...
Upvotes: 1
Reputation: 786041
Use preg_replace_callback
:
$thumbnail_tag='';
$thumbnail_caption = preg_replace_callback('{<\s*img.*?/>}', function($m)
use(&$thumbnail_tag) { $thumbnail_tag=$m[0]; return '';}, $thumbnail);
Check values:
echo $thumbnail_tag . "\n";
//=> <img typeof="foaf:Image" class="img-responsive" src="/files/styles/photocomp_large/public/lovejoymask400mm_0.jpg?itok=pqICHn8s" width="960" height="656" alt="aly" title="title" />
echo $thumbnail_caption . "\n";
//=> <blockquote class="image-field-caption">test</blockquote>
Upvotes: 1