开发者

how to find and modify several elements in an array?

I have an array of names. Some names have upper case as first letter, some have space between first name and last name. It looks like this:

array(
0 => janet,
1 => John Smith,
2 => Fred,
3 => joe-hooker
)

I want everything in lowercase. If there's a space between first/last name开发者_StackOverflow社区, change the space to "-" .

How to do it in php language? Thanks!


Use strtolower to convert to lowercase and str_replace for replacements.

$array = array(
0 => 'janet',
1 => 'John Smith',
2 => 'Fred',
3 => 'joe-hooker'
);

foreach ($array as $key=>$value)
    $array[$key] = str_replace(' ','-', strtolower($value));


you can find an item in an array with the function in_array() for example

    $arra = array("Mon", "Tue", "bla", "BLavla");
    if (in_array("Wen", $arra)) 
    {
    echo "Is in";
    }

you can replace the space with '-' ,with str_replace ( $search , $replace , $subject)


$array = array(
0 => janet,
1 => John Smith,
2 => Fred,
3 => joe-hooker
)

foreach ($array as $key => $value) { // Loop through array
  if (strpos($value,' ') !== FALSE) { // Only replace if there is an space in $value
       str_replace(' ','-',$value); // Replace space to -
  }
}


<?php
$array = array(
0 => "janet",
1 => "John Smith",
2 => "Fred",
3 => "joe-hooker"
);

$array = array_map(function($el) {
    return strtolower(str_replace(" ", "-", $el));
}, $array);

var_dump($array);

Output

array(4) {
  [0]=>
  string(5) "janet"
  [1]=>
  string(10) "john-smith"
  [2]=>
  string(4) "fred"
  [3]=>
  string(10) "joe-hooker"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜