2011-08-04 5 views
0

J'ai un tableau de noms. Certains noms ont une majuscule comme première lettre, d'autres ont un espace entre le prénom et le nom de famille. Il ressemble à ceci:comment trouver et modifier plusieurs éléments dans un tableau?

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

Je veux tout en minuscules. S'il y a un espace entre le prénom et le nom, remplacez l'espace par "-".

Comment le faire en langage php? Merci!

+1

Quelle langue utilisez-vous? – Charliemops

+1

@Jenny: Dans quelle langue ?? .. – Naor

+0

désolé, j'ai oublié de mentionner php, juste édité. – Jenny

Répondre

2

Utilisez strtolower pour convertir en minuscules et str_replace pour les remplacements.

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

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

Merci, cela fonctionne parfaitement! – Jenny

0

vous pouvez trouver un élément dans un tableau avec la fonction in_array() par exemple

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

vous pouvez remplacer l'espace par '-', avec str_replace (recherche $, remplacez $, $ subject)

0
$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 - 
    } 
} 
0
<?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); 

sortie

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