如何减少这个字符串操作代码

时间:2016-04-07 06:41:11

标签: php string

我写下面的代码有点复杂。是否可以对在较少步骤内减少代码而不是级联进行任何修改。

$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] =>'美国'[2] =>'AU'[3] =>'MY'[4] =>'TH' [5]   => 'KR'[6] => 'TW')

5 个答案:

答案 0 :(得分:0)

对于如下输出:

  

数组([0] =>'IN'[1] =>'美国'[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);

答案 1 :(得分:0)

你可以这样做

$countries='IN,US,AU,MY,TH,KR,TW';     
$countries=explode(',',$countries);    
$countries2 = array_map(function($val) { return "'".$val."'";} , $countries);
print_r($countries2);

<强>输出

  

数组([0] =&gt;&#39; IN&#39; [1] =&gt;&#39;美国&#39; [2] =&gt;&#39; AU&#39; [3] =&gt;&#39;我&#39; [4] =&gt;&#39; TH&#39; [5] =&gt;&#39; KR&#39; [6] =&gt;&#39; TW& #39;)

答案 2 :(得分:0)

<?php
 $countries='IN,US,AU,MY,TH,KR,TW';
 $countries = preg_replace("/(\b)/", "'$1", $countries);
 $countries = explode(",", $countries);
 Var_dump($countries);
 ?>

链接到工作示例: 请记住更改为preg_replace http://www.phpliveregex.com/p/ff7

答案 3 :(得分:0)

您可以使用正则表达式:

$countries = 'IN,US,AU,MY,TH,KR,TW';
$countries = preg_replace('/([A-z]{2})/', "'$1'", $countries);
$countries = explode(',',$countries);

答案 4 :(得分:0)

正则表达式替换中的

$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] =&gt;&#39; IN&#39; [1] =&gt;&#39;美国&#39; [2] =&gt;&#39; AU&#39; [3] =&gt;&#39;我&#39; [4] =&gt;&#39; TH&#39;   [5] =&gt; &#39; KR&#39; [6] =&gt; &#39; TW&#39; )

参考:http://uk.php.net/manual/en/function.preg-replace.php