开发者

PHP - How can I rewrite this section to be more professional?

How can I rewrite this section to be more professional? Maybe there is some way to combine the middle 6 lines into 1 line?

if($hyperlink){
  $hyperlink_new=$hyperlink;
  $hyperlink_new=str_replace("row[0]", $row[0], $hyperlink_new);
  $hyperlink_new=str_replace("row[1]", $row[1], $hyperlink_new);
  $hyperlink_new=str_replace("row[2]", $row[2], $hyp开发者_如何学运维erlink_new);
  $hyperlink_new=str_replace("row[3]", $row[3], $hyperlink_new);
  $hyperlink_new=str_replace("row[4]", $row[4], $hyperlink_new);
  $hyperlink_new=str_replace("row[5]", $row[5], $hyperlink_new);
  echo "<a href=\"$hyperlink_new\">";
}

Thank you.


if($hyperlink){
    $hyperlink_new=$hyperlink;
    for ($i=0; $i<6; $i+=1) {
        $hyperlink_new=str_replace("row[$i]", $row[$i], $hyperlink_new);
    }
    echo "<a href=\"$hyperlink_new\">";
}


Add a loop?

if($hyperlink){
  $hyperlink_new=$hyperlink;
  for ($i=0; $i <= 5; $i++) { 
        $hyperlink_new=str_replace("row[$i]", $row[$i], $hyperlink_new);
  }      
  echo "<a href=\"$hyperlink_new\">";
}


Assuming that $row was filled with mysql_fetch_row(), you can use str_replace hability to receive arrays as parameters.

if($hyperlink){
  $hyperlink_new = str_replace(
      array("row[0]", "row[1]", "row[2]", "row[3]", "row[4]", "row[5]"), 
      $row,
      $hyperlink
    );
  echo "<a href=\"$hyperlink_new\">";
}


Just for fun, here's how to do it using a regular expression and an anonymous function callback. Probably only good for php >= 5.3.0

    $link = 'row[0] - row[1] - row[2] - row[3]';
    $rows = array( 'zero', 'one', 'two', 'three' );
    $link = preg_replace_callback( "/row\[(\d+)\]/i", function( $matches ) use( $rows ) { return $rows[$matches[1]]; }, $link );
    echo "<a href='$link'>";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜