如何在PHP中替换并返回替换的文本?

时间:2015-12-23 20:33:21

标签: php regex

我正在将图片代码从一个地方转移到另一个地方。它目前需要2个正则表达式,一个用于查找图像标记,另一个用于替换它。这可以用一个正则表达式完成吗?

<?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; ?>

缩略图看起来像:

<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>

2 个答案:

答案 0 :(得分:1)

使用preg_replace_callback

$thumbnail_tag='';
$thumbnail_caption = preg_replace_callback('{<\s*img.*?/>}', function($m) 
        use(&$thumbnail_tag) { $thumbnail_tag=$m[0]; return '';}, $thumbnail);

检查值:

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>

答案 1 :(得分:1)

您可以使用两个捕获组,每个部分一个(图像标记,文本),如下所示:

preg_match('{(<\s*img.*?/>)(.*)}',  $thumbnail, $matches);

然后$matches将包含索引0中完全匹配的字符串,您不需要,但在索引1和2中,您将找到捕获的组:

 print $matches[1]; // <img ... />
 print $matches[2]; // <blocknote>text...