In PHP how to split string on specific character and keep that character and keep that character separate ie in its own element of an array after

 You can use the explode function in PHP to split a string on a specific character. The explode function takes two arguments: the character to split the string on (called the "delimiter"), and the string to split. It returns an array of strings, with each element in the array being a part of the original string separated by the delimiter.


For example, to split a string on the character, and keep the delimiter in its own element of the resulting array, you could do the following:

Copy code

$string = "apple,banana,cherry";

$array = explode(',', $string);

print_r($array);

This would output the following:


Copy code

Array

(

    [0] => apple

    [1] => banana

    [2] => cherry

)


Note that the delimiter is not included in any of the elements of the resulting array. If you want to keep the delimiter separate, you can use the preg_split function, which allows you to specify a regular expression as the delimiter.


For example, to split a string on the character, and keep the delimiter in its own element of the resulting array, you could do the following:


Copy code

$string = "apple,banana,cherry";

$array = preg_split('/,/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

print_r($array);

This would output the following:

Copy code

Array

(

    [0] => apple

    [1] => ,

    [2] => banana

    [3] => ,

    [4] => cherry

)

As you can see, the delimiter is now included in its own element of the array.

Comments

Popular posts from this blog

How to read a single row or of multiple txt files in python

Unable to deliver the push notification using parse server