[英]PHP preg_replace: Replace all anchor tags in text with their href value with Regex
[英](preg_replace) regex replace all & in <a href=“”>
我不知道怎么辦這個:我有一個簡單的字符串,例如:
<p>Foo & Bar</p> // <-- this should still be &
<a href="http://test.com/?php=true&test=test&p=p"> // <- This string should only be affected and be changed to &
<div> Yes ü No</div> // <-- This should still be ü
<a href="http://mycoolpage.com/?page=1&fun=true&foo=bar&yes=no">
現在我要替換所有&
只有&
與preg_replace
,我試圖為此創建一個正則表達式,但不知何故,我無法讓它工作。
這是我走了多遠,它只找到了最后一個&
並且還匹配它之前的整個字符串並且找不到另一個字符串。 我究竟做錯了什么?
(?>=href\\=\\").*?(&)(?=\\")
編輯:無法使用htmlentities_decode或htmlspecialchars_decode,因為其他代碼會受到影響。
我在不深入了解PHP正則表達式API的情況下看到的自然方式是將字符串與模式匹配,直到沒有更多匹配,例如當最后一個&
被替換,將不再有匹配
$str = "<p>Foo & Bar</p> // <-- this should still be &
<a href=\"http://mycoolpage.com/?page=1&fun=true&foo=bar&yes=no\">";
$pattern = "/(href=\".*?)(&)(.*?\">)/";
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 & ....
$index = strlen($before) + strlen($left);
$str = substr_replace($str, "&", $index, strlen("&"));
}
var_dump($str);
結果:
<p>Foo & Bar</p> // <-- this should still be & <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&fun=true&foo=bar&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.