Prevent dollar sign to be added from certain strings [duplicate]

馋奶兔 提交于 2019-12-24 17:05:11

问题


I have this this array;

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

It was possibe to put dollar sign before each alphanumeric string in array, the link is here : Adding dollar sign before each string in array?

Now, Is it possible to prevent dollar sign to be added to a certain strings, for example if there is a word she, who or they in array than dollar sign should not be added to these strings?


回答1:


Going off of your old code, I amended it:

$noappend = array("she","who","they"); // add more

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

var_dump($arr);



回答2:


Define your words in an array: $no_dollar_sign = array('she', 'who', 'they');

Loop through your array and add the dollar sign to strings that are not in the $no_dollar_sign array, using in_array.

foreach($array as $key => $item){
    if(!in_array($item, $no_dollar_sign)){
        $array[$key] = '$'.$item;
    }
}

The new values will be in $array with no change to the blocked words.

If your "no dollar sign" list is significantly larger and it is not reasonable to create/manage your own list then you should define very clearly what the rules are for why something should or should not be concatenated with a $ and potentially use regex.



来源:https://stackoverflow.com/questions/25870734/prevent-dollar-sign-to-be-added-from-certain-strings

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