Hi and this function I wrote as part of a larger project and acts exactly like the php explode function. Although there a few slight differences between this function and the php explode function it can easily be tweaked to act identical. Also with this function it does not use vectors. Instead it uses an array as the result and in the result array, the combination being split will not appear in any of the strings just like the php function does.

In case your wondering how to use this function simply place in the string to split (param1) and where to split it (param2) then it will return an string array with the results. Hope you enjoy this function and that this page is a good reference...

Ancient Dragon commented: Nice :) +26
#include <string>
std::string *explode (std::string original, std::string exploder=".") {
	std::string tmp;
	int num, loc;
	while (tmp.find(exploder)!=std::string::npos) {
	std::string *result;
	result = new std::string[num];
	while (tmp.find(exploder)!=std::string::npos) {
	return result;

Really nice, thank you! I'm programming a simple server for a game of mine and I use it to get arguments from headers :3.

Sorry for being 3 months late with this. Nice function -- a couple minor tweeks to make it run faster, but nice anyway.

Why didn't you use a vector as a return-value? It seems like the logic way to go, since you can easily find out how many strings were found, which is sort of a guessing game now.

Just as a suggestion:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> explode (std::string original, unsigned char exploder='.') {
    std::stringstream sstr(original);
    std::vector<std::string> ret_val;
    std::string buffer = "";
    while (std::getline(sstr, buffer,exploder)) 
    return ret_val;

int main() {
    std::string test = "hai.test.test.testing";
    std::vector<std::string> v = explode(test);

    std::cout << "Found " << v.size() << " words: \n";
    for (size_t i = 0; i != v.size(); ++i) 
        std::cout << v.at(i) << '\n';


Just a minor point:

php explode has a third optional parameter that limits the number of times to split


std::vector<std::string> php_explode(const std::string &divide,
 const std::string &to_explode, int max_number = -1);

would be closer to the php_function signature but an easy modification to Nick's code