Click here to Skip to main content
14,924,456 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to break array of string into words.
Example code:
$sample=array('Field name email is required','email must be valid address','password is required');
?>
I want to break each element of array.

For example the first element is break into 5 parts.How can i do that.


I tried.But i am not getting solution.

This is my code:

PHP
$sample=array('Field name email is required','email must be valid address','password is required');
$count=0;
for($i=0;$i<sizeof($sample);$i++){
    echo $sample[$i]."<br>";
    $a=$sample[$i];
    $arr= explode(' ',"$sample[$i]")."<br>";
    for($j=0;$j<sizeof($arr);$j++){
         echo $arr[$i]."<br>";
         //echo $count++;
        }
    }
    //echo sizeof($arr[$j]);
    print_r($arr);


?>
Posted

you update this code.

PHP
for ($i = 0; $i < sizeof($sample); $i++) {
    echo $sample[$i] . "<br>";
    $a = $sample[$i];
    $arr = explode(" ", "$sample[$i]");
    print_r($arr);
    for ($j = 0; $j < sizeof($arr); $j++) {
	echo $arr[$j] . "<br>";
	//echo $count++;
    }
}


i think this line will not work as u expected
PHP
$arr= explode(' ',"$sample[$i]")."<br>";


if we append "
" $arr will become a string variable , and it will not be an array.
   
v2
PHP
$sample=array('Field name email is required','email must be valid address','password is required');
$count=0;
$mail="email";
for($i=0;$i<sizeof($sample);$i++){
    echo $sample[$i]."<br>";
    //$a=str_split($sample[$i],"");
    $chars = preg_split('/ /', $sample[$i]);
    //print_r($chars);
    if(array_search("$mail",$chars)){
    echo $sample[$i]."<br>";
    }
}


?>
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900