2012-12-13 43 views
0

我想將<var title="some text">Something</var>改爲<abbr title="some text">Something</abbr>。我有這個代碼,但不知何故,它不顯示我的網頁上的abbr標記:爲什麼我的正則表達式代碼不顯示html代碼?

$arr[0] = preg_replace("#<var(.*?)>(.*?)</var>#", "<abbr $1>$2</abbr>", "".$arr[0].""); 

我在做什麼錯?

+2

什麼是#符號? – Geoff

+2

您是否將返回值分配給變量?它沒有替換原地。 –

+1

@Geoff這是一個分隔符。他們可以是很多不同的東西,不僅僅是'/ pattern /' –

回答

2

是的,你應該使用一個HTML解析器,並避免使用正則表達式解析HTML:

// Load the HTML into the parser 
$doc = new DOMDocument; 
$doc->loadHTML('<var title="some text">Something</var>'); 

// Find the <var> tags, and create new <abbr> tags from them. 
foreach($doc->getElementsByTagName('var') as $var) { 
    $abbr = $doc->createElement('abbr', $var->textContent); 
    $abbr->setAttribute('title', $var->getAttribute('title')); 
    echo $doc->saveHTML($abbr); // Here is your new <abbr> tag 
} 

您可以從this demo看出,這將產生:

<abbr title="some text">Something</abbr> 
+0

其中,html解析器是這樣的? – phpheini

+0

PHP的內置DOM解析器,['DOMDocument'](http://www.php.net/domdocument)。 – nickb

+0

所以我不需要包含一個解析器類? – phpheini

0

更改"<abbr $1>$2</abbr>"改爲'<abbr $1>$2</abbr>'(注意單引號)。

請參閱single quoted strings

+0

不幸的是,這並不能解決問題。 – phpheini