将动态参数传递给函数


Passing Dynamic arguments to a function

我在下面有一个用户定义的函数:

function char_replace($line1){
    $line1= str_ireplace("Snippet:", "", $line1);
    // First, replace UTF-8 characters.
    $line1= str_replace(
    array("'xe2'x80'x98", "'xe2'x80'x99", "'xe2'x80'x9c", "'xe2'x80'x9d", "'xe2'x80'x93", "'xe2'x80'x94", "'xe2'x80'xa6"),
    array("'", "'", '"', '"', '-', '--', '...'),
    $line1);
    // Next, replace their Windows-1252 equivalents.
    $line1= str_replace(
    array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
    array("'", "'", '"', '"', '-', '--', '...'),
    $line1);
}

正在替换我爆炸的多行上的字符,除了我想将动态参数应用于函数char_replace $line很可能$line2$line3,所以我会这样转换字符: $line1 = char_replace($line1)

我想使函数参数和 str_replace/str_ireplace 参数成为动态变量,我可以像这样转换另一行: $random_line = char_replace($random_line)这可能吗?

如果我没看错,只需为函数添加返回即可。 所以:

function char_replace($string){
  $string= str_ireplace("Snippet:", "", $string);
  // First, replace UTF-8 characters.
  $string= str_replace(
  array("'xe2'x80'x98", "'xe2'x80'x99", "'xe2'x80'x9c", "'xe2'x80'x9d", "'xe2'x80'x93", "'xe2'x80'x94", "'xe2'x80'xa6"),
  array("'", "'", '"', '"', '-', '--', '...'),
  $string);
  // Next, replace their Windows-1252 equivalents.
  $string= str_replace(
  array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
  array("'", "'", '"', '"', '-', '--', '...'),
  $string);
  return $string;
}

这将允许您将任何字符串传递给函数并取回修改后的字符串。

假设你用return $line1;结束你的函数,你可以像这样调用它:

$line1 = char_replace($line1);
$line2 = char_replace($line2);
$line3 = char_replace($line3);

如何在函数定义中调用参数并不重要,它们是该函数的本地参数,并且可以在其外部具有不同的名称。

你只想在你的函数中添加 return 语句吗:

function char_replace($line1){
    $line1= str_ireplace("Snippet:", "", $line1);
    // First, replace UTF-8 characters.
    $line1= str_replace(
    array("'xe2'x80'x98", "'xe2'x80'x99", "'xe2'x80'x9c", "'xe2'x80'x9d", "'xe2'x80'x93", "'xe2'x80'x94", "'xe2'x80'xa6"),
    array("'", "'", '"', '"', '-', '--', '...'),
    $line1);
    // Next, replace their Windows-1252 equivalents.
    $line1= str_replace(
    array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
    array("'", "'", '"', '"', '-', '--', '...'),
    $line1);
    return $line1;
}