2015-04-06 76 views
0

我想格式化文本,但我不知道該怎麼辦。PHP文本格式的文本凌亂

我有文字:

Row1 
Row2 
Title 
text _ text 


text _ text 
Row1 
Row2 
Title 
text _ text 


text _ text 

我想修改它

Title 
text : text 
text : text 

Title 
text : text 
text : text 

我想刪除ROW1和2,但仍高於空行。

要刪除兩行文本和文本之間的空白在

和改造_ in :

我嘗試使用str_replace函數和preg_replace函數,但我不知道該怎麼辦。

<?php 
     if(isset($_POST["submit"])) { 
      $text = $_POST["text-ed"]; 
      $change = ' _ '; 
      $change_r = ' : '; 
      $remove_line = array("\n", "\r"); 

$rezult = preg_replace('/[\n\r]+/', '', $text); 
$rezult = str_replace(array($remove_line, $change), array('', $change_r), $text); 
      } 
    ?> 
+0

? – 2015-04-06 12:13:00

+0

我想刪除文本下面的Row1,Row2和空行:text。 – Adrian 2015-04-06 12:17:04

+0

「Row1/Row2」文字或包含一些文本的行嗎? – 2015-04-06 12:18:12

回答

1

嘗試使用此代碼:

<?php 

$text = "Row1 
Row2 
Title 
text _ text 


text _ text 
Row1 
Row2 
Title 
text _ text 


text _ text"; 

var_dump($text); 


// Delete rows 
$text = str_replace(array("Row1","Row2"), "", $text); 
// Replace the underscore 
$text = str_replace("_", ":", $text); 
// Replace all duplicate space 
$text = preg_replace('/ +/', ' ',$text); 
// Replace all duplicate newlines 
$text = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n", $text); 

var_dump($text); 
?> 

結果:

string(103) "Row1 
Row2 
Title 
text _ text 


text _ text 
Row1 
Row2 
Title 
text _ text 


text _ text" 


string(60) " 
Title 
text : text 
text : text 
Title 
text : text 
text : text" 
要刪除ROW1,行2的文字太
+0

如果使用$ text = str_replace(array(「Row1」,「Row2」),「」,$ text); 和 $文字= str_replace函數( 「_」, 「:」,$文字);只改變第一str_replace – Adrian 2015-04-06 13:12:40

+0

看到我編輯的答案:)它的工作 – 2015-04-06 13:16:53

+0

我需要更改此代碼,因爲添加文本在textarea <?php if(isset($ _ POST [「submit」])){ $ text = $ _ POST [「文字版」]; //改變 $ rezult = str_replace函數( 「 - : - 」, 「 - 」,$文字); $ rezult = str_replace(「Barcelona」,「」,$ text); } > – Adrian 2015-04-06 13:27:45