从字符串创建php变量

克里斯227

您好,我有一个脚本,可以从字符串中提取公司名称。我希望将提取的名称转换为php变量。因此,例如,第一个结果必须将Real Coffee Sweeden转换为,$RealCoffeeSweeden = 0以便我可以为其分配值

 $test='/showname/0406741848                              : Real Coffee Sweeden
/showname/0406741849                              : Healthzone SE
/showname/16133663413                             : FREE
/showname/16133663414                             : RadioPlantes Canada
/showname/16133663417                             : Dealsoftoday.Eu Canada
/showname/16136995593                             : FREE
/showname/16136995594                             : Club White Smile Canada
/showname/16138007442                             : FREE
/showname/16138007547                             : Mybitwave.com Canada
/showname/16465596150                             : BABY
/showname/16465696956                             : FREE
/showname/16465696957                             : FREE
/showname/16467419944                             : Mybitwave.com UK
/showname/16469181975                             : FREE
/showname/21501350                                : SecureSurf.EU NO
/showname/21501351                                : FileCloud365 Norwegian
/showname/21501352                                : FREE
/showname/21501353                                : RadioPlantes Norwegian
';


$myRows= explode("\n", $test);

foreach( $myRows as $key => $value) {
    $pieces = explode(":", $value);

    $result[] =  $pieces[1];
}

foreach ($result as $res){
    $res // covert to php variable
    //example: $RealCoffeeSweeden = 0;
}
曼努埃尔·曼哈特(Manuel Mannhardt)

您应该为此使用数组。但是,如果您想以编写方式进行操作,则可以简单地执行以下操作:

foreach( $myRows as $key => $value) {
    $pieces = explode(":", $value);

    $res = str_replace(' ', '', $pieces[1]); // replace whitespaces for valid names
    $$res = 0; // note the double dollar signs
}

如果要使用数组tho,请执行以下操作:

$result = [];
foreach( $myRows as $key => $value) {
    $pieces = explode(":", $value);

    $key = str_replace(' ', '', $pieces[1]);
    $result[$key] = 0;
}

根据您的评论,使用以下命令更改foreach循环中的倒数第二行:

$res = str_replace(' ', '', $res) . '_f';

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章