在数组中的每个字符串前添加美元符号?

时间:2014-09-16 12:18:01

标签: php arrays preg-replace preg-match substr

我有这个字符串:$str = "(he+is+genius*2)/clever";在数组中看起来像这样;

Array ( 
  [0] => ( 
  [1] => he 
  [2] => + 
  [3] => is 
  [4] => + 
  [5] => genius 
  [6] => ) 
  [7] => * 
  [8] => and 
  [9] => / 
  [10] => clever ) 

我想要做的是在$str中的每个字符串之前放置美元符号$,但忽略非字母数字和数字。  最后,我希望有一些看起来像这样的东西;

$newstr = "($he+$is+$genius*2)/$clever";

2 个答案:

答案 0 :(得分:3)

对于每个值,检查第一个字符(或整个值)是否由ctype_alpha的字符组成,然后加上$

// $arr is your array as defined in your question
foreach ($arr as &$val) {
 //OR if (ctype_alpha($val[0])) { 
 if (ctype_alpha($val)) {
   $val = '$' . $val;
 }
}

var_dump($arr);

输出:

array(6) {
  [0]=>
  string(3) "$he"
  [1]=>
  string(1) "+"
  [2]=>
  string(3) "$is"
  [3]=>
  string(1) "+"
  [4]=>
  string(7) "$genius"
  ...
}

第二个解决方案,检查它是否在任何位置都有一个字符:

foreach ($arr as &$val) {
  $tmp = str_split($val); 
  foreach ($tmp as $char) {
    if (ctype_alpha($char)) {
      $val = '$' . $val;
      break;
    }
  } 
}

答案 1 :(得分:0)

只需使用array_map映射数组,并使用ctype_alpha检查其值是否为字符串,并将$连接到它。

$array = array ( 
0 => "(",
1 => "he",
2 => "+",
3 => "is",
4 => "+",
5 => "genius",
6 => ")",
7 => "*",
8 => "and",
9 => "/", 
10 => "clever"
);

$strA = array_map (function($a) {
    if (ctype_alpha($a)) // if only alphabetic characters return it with dollar sign
        return "$".$a;
    return $a; // else return normal
}, $array );

echo implode("",$strA); // ($he+$is+$genius)*$and/$clever