Adding dollar sign before each string in array?

大兔子大兔子 提交于 2019-12-02 16:35:18

问题


I have this string: $str = "(he+is+genius*2)/clever"; which looks like this in array;

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

What I want to do is placing dollar sign $ before each string present in $str but ignoring non-alphanumeric and numbers. At the end i want to have something which looks like this;

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

回答1:


For each value, check if the first char (or the whole value) is made of characters with ctype_alpha, then prepend with $ :

// $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);

Output :

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

Second solution, checking if it has a char at any position :

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



回答2:


Just map the array using array_map and check if their values are string or not with ctype_alpha, concatenating the $ to it.

$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


来源:https://stackoverflow.com/questions/25868547/adding-dollar-sign-before-each-string-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!