【问题标题】:(preg_replace) regex replace all &amp in <a href="">(preg_replace) 正则表达式替换 <a href=""> 中的所有 &amp
【发布时间】:2016-08-05 11:19:18
【问题描述】:

我不知何故无法让它工作: 我有一个简单的字符串,例如:

<p>Foo &amp; Bar</p> // <-- this should still be &amp;
<a href="http://test.com/?php=true&amp;test=test&amp;p=p"> // <- This string should only be affected and be changed to &
<div> Yes &uuml; No</div> // <-- This should still be &uuml;

&lt;a href="http://mycoolpage.com/?page=1&amp;amp;fun=true&amp;amp;foo=bar&amp;amp;yes=no"&gt;

现在我想用&amp;amp; 替换所有&amp;amp;preg_replace,我试图为此创建一个正则表达式,但不知何故我无法让它工作。

这就是我已经走了多远,它只找到最后一个 &amp;amp; 并且还匹配它之前的整个字符串并且找不到另一个。我做错了什么?

(?&gt;=href\=\").*?(&amp;amp;)(?=\")

编辑:不能使用 htmlentities_decode 或 htmlspecialchars_decode,因为还有其他代码会受到影响。

【问题讨论】:

  • 试过html_entity_decodeideone.com/6DyYuQ
  • 或者更难的方式:ideone.com/ADku3b
  • 我会试试while(regex match) { str replace }
  • 请再次检查问题,我添加了一些内容。

标签: php regex preg-replace


【解决方案1】:

我在不深入了解 PHP regex API 的情况下看到的自然方式是将字符串与模式匹配,直到没有更多匹配项,例如当最后一个&amp;amp; 被替换时,将不再有匹配项

$str = "<p>Foo &amp; Bar</p> // <-- this should still be &amp;
    <a href=\"http://mycoolpage.com/?page=1&amp;fun=true&amp;foo=bar&amp;yes=no\">";
$pattern = "/(href=\".*?)(&amp;)(.*?\">)/";


while (preg_match_all($pattern, $str, $matches)) {
    $left = $matches[1][0]; // e.g. href="http://....?page=1
    $before = substr($str, 0, strpos($str, $left)); // <p>Foo &amp; ....
    $index = strlen($before) + strlen($left);
    $str = substr_replace($str, "&", $index, strlen("&amp;"));
}

var_dump($str);

结果:

<p>Foo &amp; Bar</p> // <-- this should still be &amp; <a href="http://mycoolpage.com/?page=1&fun=true&foo=bar&yes=no">

【讨论】:

    【解决方案2】:

    Wiktor Stribiżew 的这条评论奏效了:

    或者更难的方法:http://ideone.com/ADku3b

    <?php
    $s = '<a href="http://myurl.com/?page=1&amp;fun=true&amp;foo=bar&amp;yes=no">';
    echo preg_replace_callback('~(<a\b[^>]*href=)(([\'"]).*?\3|\S+)([^>]*>)~', function ($m) {
      return $m[1] . html_entity_decode($m[2]) . $m[4];
    }, $s);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2011-07-09
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多