使用正则表达式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))。如何清除这些内容将取决于您使用的格式化系统(清除空白、用下划线/短划线替换等)