簡體   English   中英

(preg_replace)正則表達式替換所有&in

[英](preg_replace) regex replace all &amp in <a href=“”>

我不知道怎么辦這個:我有一個簡單的字符串,例如:

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

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

現在我要替換所有&amp; 只有&preg_replace ,我試圖為此創建一個正則表達式,但不知何故,我無法讓它工作。

這是我走了多遠,它只找到了最后一個&amp; 並且還匹配它之前的整個字符串並且找不到另一個字符串。 我究竟做錯了什么?

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

編輯:無法使用htmlentities_decode或htmlspecialchars_decode,因為其他代碼會受到影響。

我在不深入了解PHP正則表達式API的情況下看到的自然方式是將字符串與模式匹配,直到沒有更多匹配,例如當最后一個&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">

WiktorStribiż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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM