2010-02-23 59 views
1

是否可以用<br>標記替換換行符,但忽略跟在</h1>標記後面的換行符?用br替換換行符,但在h1之後忽略換行符PHP

因此,例如,我想改變這個塊:

<h1>Test</h1> \n some test here \n and here 

要這樣:

<h1>Test</h1> some test here <br /> and here 
+0

爲什麼你會在第一個地方有這樣的代碼?看來你的原始狀況本身就是一個問題。 – newbie 2010-03-05 22:17:25

回答

1
$subject = "<h1>hithere</h1>\nbut this other\nnewline should be replaced."; 
$new = preg_replace("/(?<!h1\>)\n/","<br/>",$subject); 
echo $new; 

// results in: 
// <h1>hithere</h1> 
// but this other<br/>newline should be replaced. 

應該工作。這是說\ n不受H1立即preceeded>

1

使用字符串函數,而不是正則表達式,並假設</h1>標籤可以是上線(而不是隻換行)之前的任何地方:

$lines=file($fn); 
foreach ($lines as $line) { 
    if (stristr("$line", "</h1>") == FALSE) { 
    $line = str_replace("\n", "<br />", $line); 
    } 
    echo $line; 
} 

這爲你的榜樣,其結果是:

<h1>測試</h1>
一些測試這裏<br />這裏<br />