簡體   English   中英

使用正則表達式php編輯html表

[英]Edit html table using regular expressions php

我被困住了,我希望有人能幫助我。

我正在根據存儲在服務器上的文件數據創建表。 我可以根據需要填充表,但是在嘗試對文件進行全局更改時遇到麻煩。 當前在表格中有人的名字,但我想這樣做,以便我可以單擊每個人的名字並將其鏈接到他們的電子郵件地址。 這是我的代碼:

<html>
<head><title>Showing Groups</title></head>
<body>
<?php

  function DisplayRow($target) {
    print "<tr>\n";
    $parts = split(" +", $target);
    for ($i = 0; $i < 10; $i+=1) {
      print "<td>$parts[$i]</td>\n";
    }
    print "<td>\n";
    for ($i = 10; $i < count($parts); $i += 1) {
      print "$parts[$i] ";
    }
    print "</td>\n";
    print "</tr>\n";
  }

  print "<table border=1 width='95%'>\n";

  $allLines = file("cis.txt");
  foreach ($allLines as $oneLine) {     
    if (ereg("^[[:digit:]]", $oneLine)) {
      DisplayRow($oneLine);
    }  
  }
  print "</table>\n";


?>
</body>
</html>

這將產生一個這樣的表(但帶有表邊界):

32133 CIS 100P 004 3.0 MW 1230 1359 CLOU 203 Wong,Jane S

我會在第10列中輸入這些名稱,以鏈接到他們的電子郵件地址,就像我上面說的那樣。

我正在嘗試使用此:

$oneLine=ereg_replace("^[[:upper:]][[:alpha:]]+,[[:blank:]]
[[:upper:]][[:alpha:]]+$", 'x', $oneLine);

正則表達式識別出我關心的是名稱,而x只是在使用,因為我試圖查看它是否有效。 我還需要知道如何更改每個單獨的名稱,以使用名字的首字母縮寫和姓氏的最多6個字符。

謝謝!

提示:確保張貼所有信息讀者可能需要事先知道,例如您的電子郵件地址的格式。現在,在我閱讀對您的帖子的評論之前,不清楚從何處獲取地址。 有時,當在項目上工作時,您可能會忘記其他人以前從未看過它,而您可能認為某些顯而易見的事情對於Stack Overflow讀者是未知的。

對於您要執行的操作,可以使用正則表達式,但實際上並非必須如此。 根據您的技能(以及格式化源文件的嚴格程度),您可能更喜歡使用一些簡單的子字符串方法。 順便說說; 電子郵件地址中的大小寫無關緊要。 如果出於美學原因仍然喜歡某種格式,則可以使用strtoupper()strtolower()ucwords()ucfirst() 有關這些方法的更多信息,請參見PHP幫助

一個簡單的例子:

<?php
    $name =  "Wong, Jane S"; // you get this from your .txt file
    $name_parts = explode(", ", $name); // Split the string by comma+space
    // Get the first character of the second part of the split string    
    echo substr($name_parts[1], 0, 1);
    // Get the first 6 characters of the last name, or if the name is less than
    // 6 characters long, it will get get the whole name
    echo substr($name_parts[0], 0, 6);
    echo "@example.com"
?>

如果您真的想要一個正則表達式,可以嘗試如下操作:

// Get the first 1 to 6 characters in the a-z range that are before the comma
// Then get the first character after the comma and combine them
preg_match('/^([a-zA-Z]{1,6}).+,\s([a-zA-Z])/', $name, $match);
echo $match[2].$match[1]."@example.com";

請注意,在這兩個示例中,您可能必須清理電子郵件地址以確保它們僅包含有效字符(例如,電子郵件中不能包含空格,但是某些名稱確實使用了它們(例如Van Helsing ))。 如何清理這些內容取決於您使用的格式化系統(清除空白,用下划線/破折號等代替)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM