doutongxuan1614 2018-07-24 11:21
浏览 33
已采纳

PHP - 在无法确定长度时查找并替换两个变量之间的字符串

I'm trying to create a simple PHP find and replace system by looking at all of the images in the HTML and add a simple bit of code at the start and end of the image source. The image source has something like this:

<img src="img/image-file.jpg">

and it should become into this:

<img src="{{media url="wysiwyg/image-file.jpg"}}"

The Find

="img/image-file1.jpg"
="img/file-2.png"
="img/image3.jpg"

Replace With

="{{media url="wysiwyg/image-file.jpg"}}"
="{{media url="wysiwyg/file-2.png"}}"
="{{media url="wysiwyg/image3.jpg"}}"

The solution is most likely simple yet from all of the research that I have done. It only works with one string not a variety of unpredictable strings.

Current Progress

$oldMessage = "img/";
$deletedFormat = '{{media url="wysiwyg/';
$str = file_get_contents('Content Slots/Compilied Code.html');
$str = str_replace("$oldMessage", "$deletedFormat",$str);

The bit I'm stuck at is find the " at the end of the source to add the end of the required code "}}"

  • 写回答

2条回答 默认 最新

  • dou4624 2018-07-24 11:44
    关注

    I don't like to build regular expressions to parse HTML, but it seems that in this case, a regular expression will help you:

    $reg = '/=["\']img\/([^"\']*)["\']/';
    $src = ['="img/image-file1.jpg"', '="img/file-2.png"', '="img/image3.jpg"'];
    
    foreach ($src as $s) {
        $str = preg_replace($reg, '={{media url="wysiwyg/$1"}}', $s);
        echo "$str
    ";
    }
    

    Here you have an example on Ideone.

    To make it works with your content:

    $content = file_get_contents('Content Slots/Compilied Code.html');
    $reg = '/=["\']img\/([^"\']*)["\']/';
    $final = preg_replace($reg, '={{media url="wysiwyg/$1"}}', $content);
    

    Here you have an example on Ideone.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?