Reputation: 4818
I have a string, how do I convert it to an array?
After manipulating that array, how do I again make it into a string?
Do strings in PHP behave the same way as in Java?
is there a dupe for this?
Upvotes: 0
Views: 4672
Reputation: 7574
Remember, set the character encoding appropriately for your task.
mb_internal_encoding('UTF-8'); // For example.
mb_regex_encoding('UTF-8'); // For example.
$characters = mb_split("", $string); // Returns an array.
$newString = implode($charaters);
Your other option would be to loop through $characters
and concatenate the string yourself!
Upvotes: 0
Reputation: 5335
In PHP Strings can be accessed like arrays.
e.g.:
$my_string = 'abcdef';
$my_string[0] ==> 'a'
$my_string[1] ==> 'b'
If you want to convert a series of words into an array then use explode(' ',$my_string);
Note: Strings in PHP are not the same as Java. In PHP they can also represent the contents of any file.
You can learn almost anything there is to know by checking the documentation :)
Upvotes: 0
Reputation: 11519
In Java you can do String.tocharArray()
which converts the string into an array of characters. You can do a String.split(regex)
to split by a regular expression, returning a String array. A char array or String array can be looped on easily to convert back to a string.
I'm not sure what you mean by "do they behave the same". Essentially they provide the same functionality... however in Java a String is an object that can be iterated upon if need be.
Upvotes: 0
Reputation: 58425
explode ( string $delimiter , string $string [, int $limit ] )
... and after changes ...
implode ( string $glue , array $pieces )
check out http://php.net/explode
and http://php.net/implode
You can also use split or join which, as far as I know, support regex
Upvotes: 5
Reputation: 19668
à la perl
<?php
$string = 'aslkdjlcnasklhdalkfhlasierjnalskdj';
$array = array_slice(preg_split('//sx', $string), 1, -1);
?>
Upvotes: 0
Reputation: 7956
as in C, strings are arrays in php
then
<?php
$a = "hola";
for($i=0; $i < strlen($a); $i++) {
echo $a[$i] . "\n";
}
$a[2] = "-"; // will print ho-a
?>
what operation do you want to do?
Upvotes: 7
Reputation: 125526
in php you can use:
split like
Description
array split ( string $pattern , string $string [, int $limit ] )
Splits a string into array by regular expression.
or
implode
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
?>
Upvotes: 0