If I have a string such as this "Hello | I'm Ben"
and I want to edit the second section, I can use PHP explode like this
$newstring = explode("|","Hello | I'm Ben");
Once that data has been edited to something new, for example:
$newstring[1] = "I'm john";
How can I implode the string to once again be "Hello | I'm John"
?
PHP's implode function returns Hello I'm John
however it does not put the delimiters back in.
So, is there a way to implode this string and put the |
between the two exploded sections of the string?
From the documentation for implode()
:
string implode ( string $glue , array $pieces )
Where:
glue
- Defaults to an empty string.pieces
- The array of strings to implode.If you don't specify the glue
parameter in your implode()
call, an empty string will be used. In this case, you need to glue the parts with |
, so you need the following:
$newstring = implode('| ', $newstring);
echo $newstring; // => Hello | I'm john
However, I don't recommend editing values like this. Perhaps use an array instead?
You should be able to use a glue piece. simply by doing :
$foo = implode("|",$newstring);
The php implode function can be used with or without this glue piece. php implode function
Edit values using implode or explode isn't a good idea, but you can achieve by this way
$newstring = implode('| ', $newstring);
You can pass a "glue" argument to implode()
. (See the docs.)
$newstring = explode("|","Hello | I'm Ben");
$newstring[1] = "I'm john";
$newstring = implode("|", $newstring);