我在下面写的代码有点复杂。是否可以进行任何修改以在较少的步骤内减少以下代码,而不是级联它。
$countries='IN,US,AU,MY,TH,KR,TW'; //list country codes separated by comma
$countries=explode(',',$countries); //partition from ,
$countries=implode(''',''',$countries); //add ' at start and end of the country code
$countries="'".$countries."'"; //add ' to first and last country code
$countries=explode(',',$countries); //create array by breaking it from ,
print_r($countries);
输出
数组([0]=>'IN'[1]=>'US'[2]=>'AU'[3]=>'MY'[4]=>'TH'[5]=>'KR'[6]=>'TW')
$1, $2... $n
在正则表达式中的替换是对括号中匹配项的引用。$0
将是整个匹配,$1
将是第一个带括号的捕获,$2
将是第二个捕获,等等。
$1 is a reference to whatever is matched by the first (.*)
$2 is a reference to ('?|&)
$4 is a reference to the second (.*)
$countries = 'IN,US,AU,MY,TH,KR,TW';
$countries = explode(',',preg_replace('/([A-Z]{2})/', "'$1'", $countries));
print_r($countries);
输出
数组([0]=>'IN'[1]=>'US'[2]=>'AU'[3]=>'MY'[4]=>'TH'[5] =>'KR'[6]=>'TW')
参考:http://uk.php.net/manual/en/function.preg-replace.php
输出如下:
阵列([0]=>'IN'[1]=>'US'[2]=>'AU'[3]=>'MY'[4]=>'TH'[5]=>'KR'[6]=>'TW')
你可以这样做:
$countries='IN,US,AU,MY,TH,KR,TW'; //list country codes separated by comma
$countries= explode(',',$countries); //partition from ,
$countries= "'".implode("','",$countries)."'";
$countries=explode(',',$countries); //create array by breaking it from ,
print_r($countries);
你可以像一样做到这一点
$countries='IN,US,AU,MY,TH,KR,TW';
$countries=explode(',',$countries);
$countries2 = array_map(function($val) { return "'".$val."'";} , $countries);
print_r($countries2);
输出
阵列([0]=>'IN'[1]=>'US'[2]=>'AU'[3]=>'MY'[4]=>'TH'[5]=>'KR'[6]=>'TW')
您可以使用类似的正则表达式
$countries = 'IN,US,AU,MY,TH,KR,TW';
$countries = preg_replace('/([A-z]{2})/', "'$1'", $countries);
$countries = explode(',',$countries);
<?php
$countries='IN,US,AU,MY,TH,KR,TW';
$countries = preg_replace("/('b)/", "'$1", $countries);
$countries = explode(",", $countries);
Var_dump($countries);
?>
链接到工作示例:记住更改为preg_replacehttp://www.phpliveregex.com/p/ff7