2012-05-07 81 views
1

下面我有一个用户定义的函数:传递动态参数的函数

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参数是一个动态的变量,在那里我可以只是转换另一里ne像这样: $random_line = char_replace($random_line) 这可能吗?

回答

1

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

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

你如何调用的参数在函数定义并不重要,他们是局部的功能,并且可以有一个不同的名字。

+0

谢谢,所有的答案是相似的,他们都工作,但我想知道为学习目的为什么添加'返回'让它是'动态'? – Tower

+2

函数定义了运行代码的独立上下文;函数参数定义了函数的输入(它们可以用作局部变量),'return'定义输出。你可以阅读更多关于这个从PHP手册 - http://www.php.net/manual/en/functions.user-defined.php –

+0

嗯,我部分理解你的说法。 – Tower

1

你只是想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; 
} 
3

如果我读这个权利,只需添加一回功能。所以:

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; 
} 

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