且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加美元符号在阵列中的每个字符串之前?

更新时间:2023-11-07 21:40:16

有关每个值,检查第一个字符(或整个值)与而ctype_alpha 制成的字符>,然后prePEND与 $

  // $ ARR是在你的问题中定义阵列
的foreach($改编为&放大器; $ VAL){
 //或者如果(而ctype_alpha($ VAL [0])){
 如果(而ctype_alpha($ VAL)){
   $ VAL =$。 $ VAL;
 }
}后续代码var_dump($ ARR);

输出:

 阵列(6){
  [0] =>
  串(3)$他
  [1] =>
  串(1)+
  [2] =>
  串(3)$是
  [3] =>
  串(1)+
  [4] =>
  字符串(7)$天才
  ...
}

第二类解决方案,检查是否有在任何位置上的字符:

 的foreach($改编为&放大器; $ VAL){
  $ TMP = str_split($ VAL);
  的foreach($ TMP为$字符){
    如果(而ctype_alpha($字符)){
      $ VAL =$。 $ VAL;
      打破;
    }
  }
}

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";

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;
    }
  } 
}