2012-11-10 41 views
-1

可能重複:
preg_replace how surround html attributes for a string with " in PHPPHP中使用的preg_replace與雙替換單詞的報價

如何使用preg_replace()變革的所有字,它內<>=後一字雙報價環繞

$var="<myfootball figure=thin new=aux(comment); > this=Association football <name=football>" 

$var="<myfootball figure="thin" new="aux(comment);" >this=Association footballl< name="football" >" 

什麼是正規表示法做到這一點的用preg_replace()

+0

是的,這個翻了一番,因爲我必須重新制定我的問題,因爲在另一個線程中它沒有采取一個好的過程,但我已經關閉了前一個。 – Martin

+0

我沒有把這種可能性新=「aux」(aux);在我的例子中。我現在改變我的例子。親愛的 – Martin

回答

3

更換(?<==)(\b\w+\b)(?!")(?=[^<]*>)"$1"

$var = preg_replace('/(?<==)(\b\w+\b)(?!")(?=[^<]*>)/', '"$1"', $var); 

編輯(基於OP的評論和問題更新)>>

更換(?<==)(\b\S+?)(?=[\s>])(?!")(?=[^<]*>)"$1"

$var = preg_replace('/(?<==)(\b\S+?)(?=[\s>])(?!")(?=[^<]*>)/', '"$1"', $var); 
+0

它的好,但如果我有新的= aux(aux);它沒有規則。結果是new =「aux」(aux);我沒有把這種可能性放在我的例子中。我現在改變我的例子。你可以改變對新改變的迴應嗎?請 – Martin

+1

@Martin - 答案已更新。 –

1

我認爲最好把它放在2個正則表達式中。第一個表達式匹配<>之間的所有內容,第二個表達式引用=之後的文本。

$value = preg_replace_callback('|<(.*?)>|', function($matches) { 
     // $matches[1] is now the text between <and> 
     return '<'.preg_replace('|=(\w+)|', '="\\1"', $matches[1]).'>'; 
}, $var);