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

问题描述 投票:0回答:2

我有这个字符串:

$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";
php arrays preg-replace preg-match substr
2个回答
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)) { // if you have other qualifying conditions add them here
   $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;
    }
  } 
}

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
© www.soinside.com 2019 - 2024. All rights reserved.