dtnmnw3697 2016-01-26 06:28
浏览 72
已采纳

Php:当使用正则表达式在html中存在多个img标记时,如何用不同的不同内容替换src

I get html content from ckeditor and i have following html content

<p><strong>Hello</strong></p>
<p><img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABVYAAAMACAIAA" style="height:131px; width:234px" /></p>
<p><strong>How are you</strong></p>
<p><img alt="" src="data:image/png;base64,ABAXKuVAAAAA3NCSVQICAjb4U/gAAAgAElEQV" style="height:142px; width:253px" /></p>
<p><strong>Good Morning</strong></p>
<p>&nbsp;</p>

Now i want to replace src of each image tag with different image name. Let says for example

<p><strong>Hello</strong></p>
<p><img alt="" src="img.jpg" style="height:131px; width:234px" /></p>
<p><strong>How are you</strong></p>
<p><img alt="" src="test.jpg" style="height:142px; width:253px" /></p>
<p><strong>Good Morning</strong></p>
<p>&nbsp;</p>

source of image is dynamically bind. so it can be anything.after this replacement i save this html content to database.

i have done with

$image_name ='<p><strong>Hello</strong></p>
    <p><img alt="" src="img.jpg" style="height:131px; width:234px" /></p>
    <p><strong>How are you</strong></p>
    <p><img alt="" src="test.jpg" style="height:142px; width:253px" /></p>
    <p><strong>Good Morning</strong></p>
    <p>&nbsp;</p>';
    $html = preg_replace('!(?<=src\=\").+(?=\"(\s|\/\>))!', 'img.jpg',$image_name );

But this replace all src same.

I want whole content same except src of <img> tag. I need to replace this content using regex. I prefer regex because i want to save this replaced html into database. If any other solution works then that is also good.

  • 写回答

1条回答 默认 最新

  • dortmundbvb0624 2016-01-26 07:26
    关注

    I have done using DOM parser as suggestion given in comments. Following is my so

    $image_name = '<p><strong>Hello</strong></p>
    <p><img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABVYAAAMACAIAA" style="height:131px; width:234px" /></p>
    <p><strong>How are you</strong></p>
    <p><img alt="" src="data:image/png;base64,ABAXKuVAAAAA3NCSVQICAjb4U/gAAAgAElEQV" style="height:142px; width:253px" /></p>
    <p><strong>Good Morning</strong></p>
    <p>&nbsp;</p>';
    
    $doc = new DOMDocument();
    $doc->loadHTML($image_name);
    $img_tags = $doc->getElementsByTagName('img');
    
    $i=0;
    foreach ($img_tags as $t )
    {
        $savepath = 'img_'.$i.'jpg';
        $t->setAttribute('src',$savepath);
        $i++;
    }
    $cont = $doc->saveHTML();
    

    This gives me proper result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页