【问题标题】:PHP RegEx to find image-tags and replace quotesPHP RegEx 查找图像标签并替换引号
【发布时间】:2016-06-08 16:59:17
【问题描述】:

我需要一个 Php-RegEx 来查找 php 字符串中的所有图像标签并替换图像标签对象中的所有引号(如“)。

$mystring = '<p class="testclass">test tag with p</p><p><img src="test1.jpg" width="100" /></p><p><img src="test2.jpg" width="100" /></p>';

我需要的结果如下:

<p class="testclass">test tag with p</p><p><img src=:quot:test1.jpg:quot: width=:quot:100:quot: /></p><p><img src=:quot:test2.jpg:quot: width=:quot:100:quot: /></p>

我已经测试了以下代码:

$rep_html = '<p class="testclass">test tag with p</p><p><img src="test1.jpg" width="100" /></p><p><img src="test2.jpg" width="100" /></p>';
$rep_html = preg_replace('#<img ([^"]) />#',":quot:", $rep_html);

或/和:

$rep_html = preg_replace('#<img ([\x22]) />#',":quot:", $rep_html);

... 不幸的是,代码不是这样工作的。引号未格式化为 :quote:。

我不需要 Php "domDocument" 和 "loadHTML" ...只有 Php RegEx ...

也许有人可以帮助我?

【问题讨论】:

    标签: php regex image replace tags


    【解决方案1】:

    我已经测试了以下代码:

    $rep_html = '<p class="testclass">test tag with p</p><p><img src="test1.jpg" width="100" /></p><p><img src="test2.jpg" width="100" /></p>';
    $rep_html = preg_replace('#<img ([^"]) />#',":quot:", $rep_html);
    

    或/和:

    $rep_html = preg_replace('#<img ([\x22]) />#',":quot:", $rep_html);
    

    ... 不幸的是,代码不是这样工作的。引号未格式化为 :quote:。

    【讨论】:

    • 我编辑了你的问题并包含了代码,如果可以的话!
    【解决方案2】:

    搜索

    <(?!img)[^>]*>[^<]*(*SKIP)(*FAIL)|"
    

    替换为

    :quot:
    

    Regex101 Example 和左侧的 code generator 为您提供代码的转义 PHP 版本。

    【讨论】:

      【解决方案3】:

      用更少的步骤,你可以使用这个模式:

      \G(?:(?!\A)|[^<]*+(?:<(?!img)[^>]*+>[^<]*+)*+<)[^">]*+\K"
      

      demo

      或者您可以使用带有 S 修饰符的 @OnlineCop 模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-05
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 2015-09-19
        • 2011-09-14
        相关资源
        最近更新 更多